tips
159 tips Web development
One command, setting or habit at a time about Web development: what it does, the line to copy and a caveat or two.
Web development 159
-
Pause a Node.js script on line one so a debugger can attach before anything runs
node --inspect-brk app.js -
Wipes storage and cache for the current site only, leaving other sites alone.
-
Pauses the debugger on a line only when your condition is true.
user.id === 42 -
Finds page elements with an XPath expression and returns them as an array.
$x(path [, startNode]) -
Captures a report of all colors, fonts, unused declarations and media queries on a page.
-
Switches the page between light and dark styling from inside DevTools.
@media (prefers-color-scheme: dark) { -
Prints an error to the console only when the checked condition fails.
console.assert(items.length > 0, 'cart is empty', items) -
Turns the entire page into an editable document so you can type over any text.
document.designMode = "on" -
Logs a stack trace so you can see which code path called a function.
function save(item) { -
Opens a page's source at a given line using a #line anchor.
view-source:https://www.mozilla.org/#line100 -
Reads a property or calls a function only when the value in front of it exists.
obj?.prop -
Turns a template literal into a string where backslashes stay as written.
const filePath = String.raw`C:\Development\profile\about.html`; -
Capture DNS, proxy and connection problems that the Network panel cannot explain.
chrome://net-export/ -
Test a site without your extensions, cookies and settings getting in the way.
google-chrome --user-data-dir=/tmp/chrome-clean --no-first-run -
Reach a test site over plain HTTP again after Chrome insisted on HTTPS.
chrome://net-internals/#hsts -
Change a header or body and send the request again from the browser.
right-click the request > Edit and Resend -
Write longer snippets in the console without Enter running them too early.
Windows and Linux: Ctrl+B -
See your design the way someone with colour vision deficiency might.
Accessibility tab > Simulate -
See grid lines, line numbers and area names directly over the page.
Inspector > click the "grid" badge -
Count the live objects of one type while hunting a memory leak.
queryObjects(Promise) -
Open the Elements panel on exactly the node your selector returns.
inspect(document.querySelector('footer')) -
Watch a value update by itself instead of typing it again and again.
Console > Create Live Expression -
Test location based features as if you were somewhere else.
type "sensors" > Show Sensors > Geolocation -
Check what a server or script sends when the browser claims to be different.
User agent > untick "Use browser default" -
Find animations and widgets that redraw far more than they need to.
Show Rendering > Paint flashing -
Get a tidy picture of a single card or table without cropping by hand.
right-click the node > Capture node screenshot -
Turn something you found by clicking into a variable you can script.
right-click the node > Store as global variable -
Write import statements without long URLs and without a build step.
import { format } from "dates"; -
Make a short silent clip start by itself without taking over the screen.
width="640" height="360" poster="demo.jpg"> -
Group the choices of a select so people find theirs faster.
-
Offer subtitles on a self hosted video with a WebVTT file.
srclang="en" label="English" default> -
Ask search engines not to list a thank you page or a draft.
-
People can paste your site address into a reader and it finds the feed.
title="Example blog" href="/feed.xml"> -
Stop screen readers from announcing file names of pictures that mean nothing.
-
Fingerprint text or a file in the page without adding a library.
async function sha256(text) { -
Show the picked image at once, without sending it to a server first.
url = URL.createObjectURL(file); -
Make a filtered view shareable without adding a history entry per click.
function setFilter(name, value) { -
Indent XML for reading and find where a broken document goes wrong.
xmllint --format feed.xml -
React to an element's own width changes, from a sidebar toggle or new content.
const observer = new ResizeObserver((entries) => { -
One button submits without validation while the main button still checks everything.
Save draft -
Fields for usernames, commands or codes stop getting red lines and corrected words.
spellcheck="false" -
Disable a whole group of inputs while a form is being sent, with one attribute.
const form = document.querySelector("#settings"); -
Validate and resolve URLs without exceptions in your normal code path.
URL.parse("not a url"); // null -
See the request that caused a redirect instead of an empty list after navigation.
Network panel > tick "Preserve log" in the toolbar -
Link to the exact sentence you mean, even on a page without anchors.
https://example.com/docs/setup#:~:text=back%20up%20the%20database -
A form result updates in place and is read out without moving focus.
Total: € <output name="total" for="qty">9.00</output> -
Sign-up and password change forms get generated passwords instead of an autofilled old one.
-
An upload button on a phone goes straight to the camera instead of the file picker.
accept="image/*" capture="environment"> -
Let visitors share a page to any app they have installed, with a fallback for desktops.
shareButton.addEventListener("click", async () => { -
Handle errors from functions that might be sync or async in one catch.
if (!name) throw new Error("No name given"); // sync throw -
One listener on a parent handles clicks on items that are added later.
list.addEventListener("click", (event) => { -
A built-in gauge that changes color based on ranges you define.
low="0.7" high="0.9" optimum="0.2">92%</meter> -
Turn codes like DE or EUR into readable names without a translation file.
const regions = new Intl.DisplayNames(["nl"], { type: "region" }); -
Turn any request a page made into code you can tweak and run again.
Network panel > right-click the request > Copy > Copy as fetch -
Choose the right plural or ordinal suffix for a number without if statements.
// 1st 2nd 3rd 4th 11th 12th 21st 22nd -
A save button in a sticky footer can still submit a form elsewhere in the page.
-
Find the stylesheets and scripts that mostly ship dead weight to a page.
choose "Per function" or "Per block" > click the reload button in the panel -
Natural sort order for file names and versions, ignoring upper and lower case.
const collator = new Intl.Collator("en", { numeric: true, sensitivity: "base" }); -
Set a breakpoint on a function without finding it in the Sources panel.
// DevTools pauses on the first line of the function -
Combine several abort reasons into one signal for fetch or any other API.
const signal = AbortSignal.any([ -
Phones download a small file and large screens a sharp one, from one img tag.
srcset="photo-400.jpg 400w, -
One click on a code snippet selects all of it, ready to copy.
user-select: all; -
Map, filter and limit any iterator lazily, even an endless one.
function* naturals() { -
Group or count items in a Map without the has, set, get dance.
// Map { "jpg" => ["a.jpg", "c.jpg"], "png" => ["b.png"] } -
Store small bits of state in the markup and read them without getAttribute.
delete item.dataset.status; // removes the attribute -
Detect added, removed or changed elements without polling the DOM.
const observer = new MutationObserver((mutations) => { -
Compress a large JSON export or upload with a built-in stream.
const stream = new Blob([text]).stream() -
Script-triggered submits check required fields and fire the submit event, unlike submit().
// submit when the user presses Ctrl+Enter in the textarea -
A modal closes on a backdrop click or Escape without a custom click handler.
-
Get the libcurl options behind a command line, as a starting point for your own code.
curl --libcurl code.c -s -H 'Accept: application/json' https://example.com/api/items -
Add months and count days between calendar dates, without midnight and DST surprises.
const start = Temporal.PlainDate.from("2026-01-31"); -
Stop a phone from dimming while someone follows steps on your page.
let lock = null; -
Get a real character count for limits and truncation, where string length is wrong.
const text = "👍🏽 ok 🇳🇱"; -
Buttons can open modals and toggle popovers declaratively, with no JavaScript.
-
Pick defer for scripts that depend on each other and async for independent ones.
-
React in a script when the visitor switches between light and dark mode.
const dark = window.matchMedia("(prefers-color-scheme: dark)"); -
Search for literal text such as 1.5 (beta)? without the dots and brackets acting as regex syntax.
const query = "1.5 (beta)?"; -
Builds a plain object from an array or Map of key-value pairs, handy after filtering entries.
const safe = Object.fromEntries( -
Resolves with the first promise that succeeds and only fails when all of them fail.
const data = await Promise.any([ -
Returns a copy of an array with one index replaced, so the original stays unchanged.
const arr = [1, 2, 3, 4, 5]; -
Removes several event listeners at once by aborting a shared AbortController signal.
const controller = new AbortController(); -
Checks whether an object has its own key, even for objects without a prototype.
const foo = Object.create(null); -
Assigns a default value only when the variable is null or undefined, keeping 0 and empty strings.
options.duration ??= 100; -
Replaces every occurrence of a string in one call, with no regex escaping.
"192.168.1.10".replaceAll(".", "-"); -
Runs tests with the test runner built into Node, no extra package needed.
test("async tests work too", async () => { -
Shows the chain of dependencies that caused a package to be installed.
npm explain glob -
Prints how long code took between two labelled console calls.
console.time("fetchData"); -
Maps an array and drops or adds items in one pass by returning arrays.
const a = [5, 4, -3, 20, 17, -33, -4, 18]; -
Formats dates and times in Dutch or any locale with the built-in Intl object.
// for example "28 november 2026 om 14:05" -
Returns every regex match including capture groups, readable with named groups.
const re = /(?<year>\d{4})-(?<month>\d{2})/g; -
Waits for an async iterable or list of promises and returns a normal array.
async function* pages() { -
Sets the label of the Enter key on mobile keyboards, like search, next or send.
-
Offers suggestions under a text input while still allowing any typed value.
-
Colors the browser toolbar to match your site, with separate light and dark values.
-
Hides content but lets browser search and #links still find and reveal it.
-
Marks places where a long URL or path may wrap, without adding a hyphen.
https://example.com<wbr>/some<wbr>/very<wbr>/long<wbr>/path<wbr>/to<wbr>/a-file.pdf -
Makes a link save the file with a name you suggest, only for same-origin URLs.
-
Gives a visible date a precise machine-readable value for browsers and scripts.
-
Marks the search or filter part of a page as a landmark without an ARIA role.
-
Hints that an image can be decoded after the rest of the page has painted.
width="800" height="600" decoding="async"> -
Prints a message to the Console each time a line runs, without pausing the page.
'cart total', total, items.length -
Pauses the page in the script that adds, removes or changes an element.
Elements > right-click #results > Break on > Subtree modifications -
Logs the events fired on the element you last inspected, straight from the Console.
monitorEvents($0, 'click') -
Shows every event listener registered on the element you just inspected.
getEventListeners($0) -
Copies the result of a console expression to the clipboard as text.
copy($$('a').map(a => a.href)) -
Edits an HTTP response header in Chrome so you can test a fix before changing the server.
-
Filters the Network panel down to requests bigger than a size you choose.
larger-than:500k -
Copies every request still visible in a filtered Network list as cURL commands.
method:POST -
Saves the network log as a HAR file without cookie and authorization headers.
-
Saves JavaScript in DevTools so you can run it on any page with one shortcut.
console.table([...document.querySelectorAll('img')].map(i => i.src)) -
Keeps an element in its hover state so you can edit the matching CSS.
Elements > Styles > :hov > :hover -
Makes Chrome behave as if reduced motion is switched on, to test your CSS.
@media (prefers-reduced-motion: reduce) { .hero { animation: none; }} -
Saves a PNG of a web page from the terminal, with no browser window.
google-chrome --headless --screenshot --window-size=1280,1696 https://example.com -
Prints the page's HTML as it looks after JavaScript has run.
google-chrome --headless --dump-dom https://example.com -
Captures the entire web page, including what is below the fold, as a PNG file.
:screenshot --fullpage -
Blocks requests to a URL fragment from the Firefox console, to test failures.
:block analytics.example.com -
Slows the network in Firefox's responsive view to test a page on a weak connection.
Ctrl+Shift+M > No throttling > Good 3G -
Finds elements by CSS selector in the Firefox console, including inside shadow DOM.
$$$('button') -
Saves a screenshot of the entire page at the width you chose in device mode.
Toggle device toolbar > More options > Capture a full size screenshot -
Pauses the debugger on the line that sends a request whose URL contains your text.
/api/orders -
Finds a piece of text in every file the page has loaded, from one search box.
Ctrl+Shift+F > Authorization -
Joins an array into a readable sentence list using the rules of a language.
const cities = ["Leiden", "Delft", "Utrecht"]; -
Stops translation tools from translating code, commands and product names on a page.
and open <span translate="no">Home Assistant</span> in your browser. -
Sends a message from one browser tab to all other open tabs of the same site.
// in the tab where the user clicks "log out" -
Keeps the original error attached when you catch it and throw a clearer one.
throw new Error("Could not load settings", { cause: err }); -
Sends a small POST request reliably when a visitor leaves or hides the page.
const data = JSON.stringify({ path: location.pathname, seconds: timeOnPage }); -
Creates a promise and hands you its resolve and reject functions to call later.
const { promise, resolve, reject } = Promise.withResolvers(); -
Formats prices and large numbers per language and currency, without your own string code.
new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" }).format(123456.789); -
Runs code when an element enters the viewport, without listening to every scroll event.
const observer = new IntersectionObserver((entries) => { -
Lets the browser set up the connection to a critical third-party server before it is needed.
-
Keeps a block of HTML ready but hidden, so a script can copy it for each new item.
-
Finds the last array item that matches a test, without reversing or copying the array.
[5, 12, 50, 130, 44].findLast((element) => element > 45); -
Tells the browser which image matters most, so the main picture of a page appears sooner.
-
Makes a menu or tooltip that opens and closes from a button, without writing JavaScript.
-
Makes part of a page unclickable, unfocusable and hidden from screen readers with one attribute.
...the page behind the drawer... -
Combines two JavaScript sets into a new one with a built-in method.
// Set { "docker", "tmux", "git", "python" } -
Marks an input as a one-time code field so browsers can offer the code from a text message.
inputmode="numeric" autocomplete="one-time-code"> -
Gives a text input a list of suggested values without JavaScript, while still allowing free typing.
-
Hints which virtual keyboard a phone should show for a field, without changing validation.
-
Offers the browser alternative image files by format or by media condition, with an img fallback.
-
Formats a number and a unit as relative time in a chosen language, without a library.
const rtf = new Intl.RelativeTimeFormat("nl", { numeric: "auto" }); -
Writes a string to the clipboard from JavaScript, as long as the page and the moment are allowed.
button.addEventListener("click", async () => { -
Runs several promises together and returns the outcome of each, without stopping at the first rejection.
const results = await Promise.allSettled([ -
Parses and builds URL query strings, with encoding handled for you.
const params = new URLSearchParams({ q: "fiets reparatie", page: 2 }); -
Starts a Node.js script in watch mode, so it restarts by itself each time you save a file it uses.
node --watch index.js -
Installs exactly what the lockfile says, after wiping node_modules, so builds are the same every time.
npm ci -
Shows the top-level dependencies of a project without the long tree of dependencies below them.
npm ls --depth=0 -
Lists installed packages with their current, wanted and latest versions, without changing anything.
npm outdated -
Opens a real modal dialog with a backdrop, focus handling and Escape to close, using one HTML element.
Delete this item? -
Reads an array item by index and counts from the end when the index is negative.
const items = ['a', 'b', 'c']; -
Returns a random version 4 UUID from the browser's secure random generator.
const id = crypto.randomUUID(); -
Groups the items of an array into an object, one array per key you compute.
const files = [ -
Makes a fetch request give up after a set number of milliseconds, without a controller and a timer.
try { -
Tells the browser your page supports light and dark, so default controls match the visitor's setting.
color-scheme: light dark; -
Returns a new sorted array and leaves the array you started with as it was.
const sorted = names.toSorted(); -
Opens a searchable command menu in Chrome DevTools, for example for full-page screenshots.
-
Makes a click-to-expand block in plain HTML, with no JavaScript.
-
Makes a full deep copy of a JavaScript object, including dates, maps and sets.
const copy = structuredClone(original); -
Gives an element a fixed width-to-height ratio with one CSS line.
.video {
Nothing in this filter yet.