Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Next.js and React

Reading localStorage inside an iframe throws a SecurityError

ErrorFailed to read the 'localStorage' property from 'Window': Access is denied for this document.

Short answer

localStorage throws a SecurityError when the document has no usable origin or the browser blocks storage for it. In an iframe the usual reasons are a sandbox attribute without allow-same-origin, or the user blocking cookies and site data. Allow the token, wrap access in try/catch, and fall back to memory.

  • Applies to Chrome current release, Firefox current release, Safari current release
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 1Find out which cause you have

    In the iframe's own console context, check which origin the document has and whether storage can be touched at all.

    console.log(window.origin)  // "null" means an opaque origin
    try { localStorage.setItem('t', '1'); localStorage.removeItem('t'); console.log('ok') }
    catch (e) { console.log(e.name, e.message) }
  2. 2Match what you see, then jump to its fix

    1. 1window.origin prints null inside the frame.The iframe has a sandbox attribute without allow-same-originFix
    2. 2window.origin is null although there is no sandbox attribute.The framed page is served from a data: or file: URLFix
    3. 3The error appears for some visitors only, and the sandbox is fine.The browser is set to block cookies or site dataFix
    4. 4The frame is on another site and sees empty storage, or none, when the browser blocks third-party cookies.A third-party frame needs its cookies, not a fresh partitionFix

What does the error look like?

  • Failed to read the 'localStorage' property from 'Window': Access is denied for this document.
  • Uncaught DOMException: Failed to read the 'localStorage' property from 'Window'
  • SecurityError

Cause 1 of 4

The iframe has a sandbox attribute without allow-same-origin

1Check

MDN says that without allow-same-origin the embedded resource is treated as a special origin that always fails the same-origin policy, which can block storage and cookies. Look at the sandbox attribute on the iframe tag in the parent page.

document.querySelector('iframe').getAttribute('sandbox')

2Fix

Add allow-same-origin only if the framed page is your own. MDN strongly discourages allow-scripts together with allow-same-origin for a same-origin document, because the frame can then remove its own sandbox. For content you do not control, leave the sandbox alone and do not use localStorage in it.

<iframe src="/widget" sandbox="allow-scripts allow-same-origin"></iframe>

3Verify

Reload the page and run the first-step snippet again. It should print ok.

console.log(window.origin)

Confirmed by developer.mozilla.org

Did this fix it?

Cause 2 of 4

The framed page is served from a data: or file: URL

1Check

MDN lists the case where the origin is not a valid scheme, host and port tuple, for example file: or data:, as a reason for SecurityError.

console.log(location.href.slice(0, 30))

2Fix

Serve the page over http or https from a real host, even localhost during development.

<!-- use an http(s) address, not file:// or data: -->
<iframe src="http://localhost:3000/widget"></iframe>

3Verify

Open the page from the new address and repeat the storage test.

console.log(window.origin)

Confirmed by developer.mozilla.org

Did this fix it?

Cause 3 of 4

The browser is set to block cookies or site data

1Check

MDN says that when a user blocks cookies, browsers will probably read that as an instruction to prevent the page from persisting data, and localStorage then throws.

try { localStorage.getItem('x') } catch (e) { console.log(e.name) }

2Fix

Your code cannot override the user's choice. Wrap every storage call in try/catch and fall back to a variable in memory, so the widget still works.

let store;
try { store = window.localStorage; store.getItem('x'); }
catch { const m = new Map(); store = { getItem: k => m.get(k) ?? null, setItem: (k, v) => m.set(k, String(v)), removeItem: k => m.delete(k) }; }

3Verify

Block site data in the browser settings and reload. The widget should run without a thrown error.

store.setItem('t', '1'); console.log(store.getItem('t'))

Confirmed by developer.mozilla.org

Did this fix it?

Cause 4 of 4

A third-party frame needs its cookies, not a fresh partition

1Check

Chrome partitions localStorage in a third-party iframe per top-level site, so data written under site a.com is not seen under site b.com. The Storage Access API is how an embed asks for unpartitioned access.

document.hasStorageAccess().then(console.log)

2Fix

From a click handler inside the frame, call requestStorageAccess and reload the frame after it resolves. If the frame is sandboxed, the sandbox needs allow-storage-access-by-user-activation together with allow-scripts and allow-same-origin.

button.addEventListener('click', async () => {
  await document.requestStorageAccess();
  location.reload();
});

3Verify

After the reload, hasStorageAccess should resolve to true.

document.hasStorageAccess().then(console.log)

Confirmed by developer.mozilla.org

Did this fix it?

How do I stop it coming back?

  • Never assume localStorage exists; wrap it in try/catch from the first line.
  • Give iframes you own the smallest sandbox that works, and add allow-same-origin deliberately.
  • Serve widgets from a real https origin, not data: or file: URLs.
  • Keep important state on the server, so blocked browser storage does not lose it.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Related fixes

Web apps

tsconfig rejects allowImportingTsExtensions

An error that allowImportingTsExtensions needs noEmit or emitDeclarationOnly

allowImportingTsExtensions lets files import each other with .ts or .tsx extensions, and TypeScript only allows it together with noEmit or emitDeclarationOnly.

2 causes, each with a fix

Web apps

A POST to a Google Apps Script web app returns 405 or a CORS error

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Apps Script web apps run doPost for POST and doGet for GET, and the Apps Script guides describe no other entry points.

3 causes, each with a fix

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.