Web developers and quality assurance engineers frequently run repetitive JavaScript routines in browser consoles to audit DOM structures, extract metadata, mock API responses, or inspect accessibility attributes. While pasting scripts directly into the interactive Console works for one-off tasks, managing multi-line debugging scripts across sessions often leads to lost code or accidental syntax errors. Apple Safari Web Inspector provides a dedicated Snippets feature that lets you author, store, edit, and execute persistent JavaScript scripts directly within the developer environment across any open webpage.
Enabling Safari Web Inspector and Navigating to Snippets
Before managing snippets, ensure Safari Developer tools are active on macOS:
- Open Safari, click the Safari menu in the menu bar, and choose Settings (or press Command + Comma).
- Navigate to the Advanced tab.
- Check the box labelled Show features for web developers (or Show Develop menu in menu bar on earlier macOS versions).
- Close Settings and press Option + Command + I on any webpage to open the Web Inspector.
- In the Web Inspector toolbar, select the Sources tab.
In the primary navigation sidebar on the left side of the Sources tab, locate the Snippets section located beneath the resource tree. If the section is collapsed, click the disclosure arrow to expand it.
Creating and Naming a New Snippet
Safari stores snippets globally within your user developer profile, meaning any script created in Snippets remains accessible across different tabs, domains, and browser restarts.
To create a new snippet:
- Click the + (Plus) icon in the navigation bar header or right-click within the Snippets container and select Create Snippet.
- A new entry appears in the list, typically titled Untitled.
- Type a descriptive name that clarifies its technical function (for example,
Audit-Images.js,Extract-Meta-Tags.js, orHighlight-Layout-Shifts.js) and press Return.
Selecting the snippet opens a full-featured code editor in the central panel of Web Inspector, complete with JavaScript syntax highlighting, line numbers, automatic bracket pairing, and code folding.
Authoring Practical Debugging Snippets
Snippets execute within the execution context of the currently selected frame in the webpage. You can author comprehensive scripts that interact directly with the live DOM, window variables, and modern web APIs.
Example 1: Auditing Missing Image Dimensions and Alt Attributes
This snippet scans all images on the active page, flagging assets missing accessibility labels or explicit dimensional sizing that can cause Cumulative Layout Shift (CLS):
(() => {
console.group("Image Accessibility and CLS Audit");
const images = Array.from(document.querySelectorAll("img"));
let warnings = 0;
images.forEach((img, index) => {
const missingAlt = !img.hasAttribute("alt") || img.getAttribute("alt").trim() === "";
const missingDimensions = !img.hasAttribute("width") || !img.hasAttribute("height");
if (missingAlt || missingDimensions) {
warnings++;
console.warn(`[#${index + 1}] Source: ${img.src || img.getAttribute("data-src") || "inline"}`, {
missingAlt,
missingDimensions,
element: img
});
}
});
console.log(`Audit complete: ${images.length} total images analysed, ${warnings} issues flagged.`);
console.groupEnd();
})();
Example 2: Monitoring Unhandled Promise Rejections
To catch asynchronous errors that might bypass standard try-catch blocks during exploratory testing, you can register global event listeners via a snippet:
(() => {
window.addEventListener("unhandledrejection", (event) => {
console.error("Unhandled Promise Rejection Detected:", {
reason: event.reason,
promise: event.promise,
timestamp: new Date().toISOString()
});
});
console.info("Registered global unhandled promise rejection listener via Safari Snippet.");
})();
Running and Testing Snippets
Safari provides multiple convenient methods to execute your saved snippets:
- Quick Execution Shortcut: While editing a snippet in the Sources tab, press Command + Return. The snippet runs immediately in the active browsing context.
- ContextMenu Execution: Right-click the snippet name in the navigation sidebar and choose Run Snippet.
- Run Button: Click the small triangular Play button located at the bottom-right or top-right corner of the snippet editor pane.
Switch to the Console drawer (press Escape while in Sources or click the Console tab) to view all output, warnings, errors, and returned values generated by the snippet.
Setting Breakpoints Inside Snippets
Safari Web Inspector treats snippets as first-class source files. If you are developing complex utility logic or multi-step asynchronous scrapers, you can debug the snippet itself:
- Click on any line number in the gutter of the snippet editor to set a breakpoint.
- Press Command + Return to trigger the snippet.
- Execution will pause at the chosen line, allowing you to step through expressions, inspect local variables in the Scope Chain panel, and evaluate expressions in the Console prompt.
Managing, Renaming, and Organising Snippets
To keep your developer workspace tidy as your snippet library grows:
- Renaming: Right-click an existing snippet in the sidebar and choose Rename Snippet, or click on an already-selected snippet name to edit the text inline.
- Duplicating: Right-click a snippet and select Duplicate Snippet to create a variant without overwriting established testing routines.
- Deleting: Select the snippet and press Delete (or right-click and choose Delete Snippet) to permanently remove scripts you no longer require.