Reading localStorage inside an iframe throws a SecurityError
Failed 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.
Fix it fast
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) }2Match what you see, then jump to its fix
- 1
window.origin prints null inside the frame.The iframe has a sandbox attribute without allow-same-originFix - 2
window.origin is null although there is no sandbox attribute.The framed page is served from a data: or file: URLFix - 3
The error appears for some visitors only, and the sandbox is fine.The browser is set to block cookies or site dataFix - 4
The 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
- 1
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
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
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
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
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 fixWeb apps
AuthUserPoolException: Auth UserPool not configured in a Next.js app
Auth UserPool not configured
The error means an Amplify Auth call ran before Amplify.configure did.
3 causes, each with a fixWeb apps
Module not found for antd/dist/antd.less after upgrading to Ant Design 5
Module not found: Error: Can't resolve 'antd/dist/antd.less'
Ant Design 5 dropped Less and the bundled CSS file for CSS-in-JS, so antd/dist/antd.less no longer exists.
3 causes, each with a fixWeb apps
Apollo Server rejects a request as a potential CSRF
HTTP 400 Bad Request from the GraphQL endpoint
Apollo Server's CSRF prevention is on by default.
3 causes, each with a fixWeb apps
Apollo Client is blocked by CORS when the GraphQL server runs on AWS Lambda
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Apollo Server does not set CORS for you when it runs behind a framework or integration, and on Lambda that layer is API Gateway.
5 causes, each with a fixWeb 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