简体   繁体   中英

Accessing localStorage for a domain via iframe

On example.com I have an iframe which loads anotherexample.com . The problem I am having though is if I load anotherexample.com directly (outside of the iframe) the localStorage isn't shared with the iframed anotherexample.com .

Is this possible to achieve?

An example of the issue can be seen by visiting https://eskimo.dev/localstorage/ , then visiting https://eskimo.ooo/localstorage/iframe which iframes the first link. The iframe isn't using the localStorage from the previous.

Actually I tried, and it worked for me (I accessed first /iframe but it worked for me both ways):

Image from https://eskimo.ooo/localstorage/iframe

Image from https://eskimo.dev/localstorage/

Image from DevTools

Of course, when I disabled all third party cookies it didn't work. Might that be the reason?

I'm using chrome 107.0 by the way.

Not sure why its not behaving as it should. May be code snippets might be really helpful here. But by the above linked example in the OP. The reason its not working there is:

  1. There are 2 domains: eskimo.dev & eskimo.ooo (Both of these are different). When the first domain eskimo.dev is opened, the local storage is set in the browser with reference to eskimo.dev and this will accessible to page with origin "eskimo.dev".
  2. But when eskimo.ooo is opened (domain that has the iframe src set to eskimo.dev) here the localStorage will not be shared as the origin domain is eskimo.ooo, and therefore cannot access localStorage data of eskimo.dev.

What will work? :

  1. If you were to have eskimo.dev/localStorage (where the localStorage is set in the browser) and
  2. now if you open eskimo.dev/localStorage/iframe (in which the iframe src points to eskimo.dev/localStorage, this page will have access to localStorage data.), why?

Because, the domain origin is not changing, hence it can access the same localStorage.

Thanks

It is a complete other domain, so there is no way access localStorage of the other domain.

But if you have control of both domains, you could use javascript events to share the localStorage through domains.

You can see more here: cross domain localstorage with javascript

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM