0

My intention: Facilitate localStorage value transfer from one domain to another

I have a page, domain.com/storage-agent.html which will be embedded in an iframe by diffdomain.com. domain.com/storage-agent.html has the following response header.

Content-Security-Policy: frame-ancestors https://diffdomain.com https://diff.domain.com

(X-Frame-Options: SAMEORIGIN also exists, but anyway, it'll be ignored by Chrome in favour of frame-ancestors.)

domain.com/storage-agent.html has a script, that will postMessage a value from localStorage (of domain.com) and the host/embedder listens to it.

The problem is, when the aforementioned script accesses localStorage.getItem('key') when it's embedded by diffdomain.com in an iframe, it's null. JSON.stringify(localStorage) is {} too, meaning none of the values are available.

But, if I load domain.com/storage-agent.html in a separate tab and do the same localStorage.getItem('key') in console, I get the value as expected.

If I embed domain.com/storage-agent.html in diff.domain.com, then also things work as expected. So nothing wrong with the script that gets from localStorage.

Can't get my head around what's happening.

karthikaruna
  • 3,042
  • 7
  • 26
  • 37
  • `Content-Security-Policy: frame-ancestors` is just defining to what ancestors an `iframe` may be embedded. That doesn't mean the two sites can access each other's local storage. The local storage in the browser is per domain and if the domain differs, you cannot access the local storage. It works for `example.com` and `api.example.com` because they are under the same domain. But it doesn't work for `example.com` and `anotherexample.com` because that are different domains – derpirscher Feb 28 '23 at 13:57
  • I'm not looking to access cross domain localStorage. I'm accessing domain.com's localStorage from a page in domain.com and looking to `postMessage` the result to the embedder. The only thing to note is, the domain.com page is embedded in an iframe by diffdomain.com. – karthikaruna Feb 28 '23 at 14:09
  • Guess what? There's an undocumented behaviour (at least in Chromium, Safari & Firefox) - if third-party **cookie**s are blocked, the rule is applied to **localStorage** as well https://stackoverflow.com/questions/30481516/iframe-in-chrome-error-failed-to-read-localstorage-from-window-access-deni. But for some reason, I didn't get this exception either. – karthikaruna Feb 28 '23 at 16:43

0 Answers0