My extension, PixLasso, saves the images on a page in two ways. One builds a ZIP in an offscreen document and hands Chrome a blob URL; I wrote about that path when I covered WebP to JPG conversion. The other saves each image as its own file: the service worker calls chrome.downloads.download once per image URL and lets Chrome fetch it.

The second path looks like one line of code. It needed a lot more than that, and these are the problems I ran into, with the code that handles each one now.

Names Chrome refuses

chrome.downloads.download({ url, filename }) rejects with "Invalid filename" when any path segment fails Chrome's net::IsSafePortablePathComponent check. Page text ends up in file names a lot (I offer {title}, {alt} and {domain} tokens), so I hit most of the list:

  • the usual illegal characters < > : " / \ | ? * and control characters
  • Windows device names, even with an extension: con, prn, aux, nul, com0 to com9, lpt0 to lpt9, clock$, so con.jpg fails too
  • desktop.ini and thumbs.db
  • a segment ending in .local or .lnk
  • a ~ at either end of a segment, and leading or trailing dots and spaces
  • zero-width and bidi control characters, noncharacters, and lone surrogates (half an emoji left behind by slice)

The sanitizer handles them in order:

const ILLEGAL = /[<>:"/\\|?*\u0000-\u001F\u007F-\u009F]/g; const RESERVED = /^((con|prn|aux|nul|com[0-9]|lpt[0-9]|clock\$)(\..*)?|desktop\.ini|thumbs\.db)$/i; export function sanitizeSegment(s, fallback = 'image') { let out = String(s ?? '') .normalize('NFC') .replace(/\p{Cf}|\p{Cs}|\p{Noncharacter_Code_Point}/gu, '') .replace(ILLEGAL, '_') .replace(/\s+/g, ' ') .trim() .replace(/^[.\s~]+|[.\s~]+$/g, ''); // ...length cut, see below... out = out.replace(/\.(local|lnk)$/i, '_$1'); if (!out || RESERVED.test(out)) out = out ? `_${out}` : fallback; return out; } 

A reserved name gets an underscore in front (clock$ becomes _clock$), and an empty result falls back to image.

Length is in bytes

Linux and macOS cap a file name at 255 bytes. A product title in Vietnamese or Japanese takes two or three bytes per character in UTF-8, so a 120-character limit is not enough on its own. I cap each segment at 120 characters and 200 bytes, which leaves room for the (12).jpeg that duplicates get and the .crdownload Chrome adds while a file is in progress.

The cut walks whole code points, so it never splits an emoji or a CJK character:

const chars = [...out]; let keep = 0; for (let bytes = 0; keep < chars.length && keep < 120; keep++) { bytes += utf8.encode(chars[keep]).length; if (bytes > 200) break; } if (keep < chars.length) out = chars.slice(0, keep).join('').replace(/[.\s~]+$/, ''); 

Page text must not create folders

filename may contain /, and Chrome creates the folders. That is useful for a folder per page, and a problem when an alt text says "T-shirt S/M/L". Every token that comes from the page has its slashes replaced before it goes into the template, the folder pattern is split on / and each segment is sanitized on its own, and . and .. segments are dropped. A URL name with an encoded %2F is decoded first and then sanitized, so it cannot sneak a slash in either. The ZIP entries go through the same function, which also rules out ZIP slip.

Duplicate names inside one batch

conflictAction: 'uniquify' handles a file that already exists on disk. It does not help when two images in the same batch get the same name and both downloads start at once. So names are built first, in page order, against a set of names already used in that batch:

let candidate = `${name}.${safeExt}`; let k = 2; const key = (c) => `${folder}/${c}`.toLowerCase(); while (used.has(key(candidate))) candidate = `${name} (${k++}).${safeExt}`; used.add(key(candidate)); 

The key is lowercased, so photo.JPG and photo.jpg count as the same file.

The worker stops at the next download

When one download fails, for example a full-size original that returns 404, Chrome can stop the extension's service worker at the next chrome.downloads.download call. Timers stop with it, so a timeout and retry inside the worker cannot help. I reproduced it in plain Chromium and in Edge 156 with a minimal extension.

The 0.1.2 release started downloads one after another, and in that case it saved between 0 and 6 of 10 images, with nothing shown in the popup. The fix was to start every download in a single pass and to delay the fallback retry by 300 ms:

// All in one pass: Chrome can stop the worker at a download() call made right after // another download failed (404s), and then nothing after it starts. await Promise.all(items.map((item, i) => { const url = item.resolvedUrl || item.fullUrl || item.url; const filename = buildPath({ /* pattern, index, page title... */ used }); return chrome.downloads.download({ url, filename, conflictAction: 'uniquify', saveAs: false }) .then((id) => { /* remember a fallback for this id */ }, (e) => failures.push({ url: item.url, error: String(e.message || e) })); })); 

With that change it saved 10 of 10 in every run.

Retrying with the page's own image

When a rewritten full-size URL fails, the extension retries with the URL the page itself used. The retry happens in chrome.downloads.onChanged, after the 300 ms delay:

if (delta.state.current === 'interrupted') setTimeout(retry, 300); else chrome.downloads.search({ id: delta.id }).then(([d]) => { if (d && isSoft404(d)) chrome.downloads.removeFile(delta.id).then(retry).catch(() => {}); }); 

The second branch exists because a download can complete and still be wrong. Some servers answer a bad image URL with an HTML page and HTTP 200, and Chrome saves it under your .jpg name. Wayfair goes further: a missing image comes back as a 513 × 321 "no image" JPEG, 37,317 bytes, with HTTP 200 and a no-image: true header. So a finished download counts as a soft 404 if its MIME type is text/html and it is under 100,000 bytes, or if it is exactly that Wayfair placeholder. The file is deleted from disk and the page's own image is saved instead.

The map from download id to fallback lives in memory. If the worker restarts in the middle of a batch, a failed original stays failed. I left a comment saying so and will persist it if someone reports it.

The extension comes from the URL

chrome.downloads needs the file name when the download starts, before any bytes arrive. So for separate files, the extension guesses the type from the URL, and falls back to .jpg when the URL says nothing.

That guess can be wrong. During Edge testing on 4 December, bing.com/sa/simg/facebook_sharing_5.png turned out to be a JPEG, and it was saved as .png. The ZIP path does not have this problem, because it reads the first bytes before naming the file. For separate files I see two options: chrome.downloads.onDeterminingFilename, which can set the name once Chrome knows the real MIME type, or accepting the mismatch and documenting it. That task is still open.

A Save As dialog outlives the worker

With "ask where to save", Chrome shows its Save As dialog. If the user leaves it open for more than 30 seconds, the idle service worker is stopped, and any in-memory map from download id to job is gone. When the user then clicks Cancel, onChanged runs in a fresh worker that knows nothing about that download. In the first version, the popup kept saying the ZIP was saved, and the blob URL stayed alive until its 30-minute safety timer.

Now the job record is written to chrome.storage.session under dl<id> when the download starts. If that is missing too, the worker asks chrome.downloads.search for the download and treats it as ours when its URL starts with this extension's blob:chrome-extension:// origin. A USER_CANCELED error on a ZIP is then reported as a cancelled save, and the blob is revoked.

A short checklist

  • Sanitize every path segment against Chrome's list, and cap names in bytes.
  • Replace slashes in page text before it reaches the template.
  • Build unique names for the batch before starting any download.
  • Start all downloads in one pass, and delay retries after a failure.
  • Check finished downloads for HTML and known placeholders.
  • Keep anything a Save As dialog depends on in chrome.storage.session.

The folder support in filename is what lets one batch from several tabs land in a folder per tab; the steps are in download images from all open tabs. I make PixLasso, a Chrome and Edge extension that saves the images on a page as a ZIP or as separate files.