简体   繁体   中英

Accessing localStorage of an iFrame in an event callback?

I'm trying to cheat a bit with localStorage. The spec defines that when a value in localStorage changes, all other open pages on the same domain receive a storage event callback. I would also like the event to fire on the page where the value was changed.

I added a hidden iFrame to each page which loads an empty document from the same domain and tried using it as the target for the localStorage change (so technically the page that I'm looking at isn't the origin of the localStorage change)

It works fine except for when I do the same thing inside an event callback...

function fnSetupMusicPlayerSection(i, oSection) {
    var oAudio, oLocalStorageFrame, oLocalStorageWindow;

    oAudio = oSection.querySelector('audio');
    oLocalStorageFrame = oSection.querySelector('iframe.local-storage-target');
    oLocalStorageWindow = oLocalStorageFrame.contentWindow || oLocalStorageFrame;

    oLocalStorageWindow.localStorage.setItem('loadSetter', '1111');

    oAudio.addEventListener('play', function(oEvent) {
        oLocalStorageWindow.localStorage.setItem('callbackSetter', '2222');
    });
}

loadSetter is successfully stored and all windows receive the storage event. When I click to play the audio I get the following error inside the callback - Uncaught DOMException: Failed to execute 'setItem' on 'Storage': access is denied for this document.

Is there anything I can do to solve this? I really don't want to have to write code to update the current page separately

Update : I don't know if I'm doing something wrong in the example I gave above but the code does seem to work inside some callbacks. I have an anchor on the page with a click event where I can set localStorage through the iFrame

You can try postMessage API to enable communication between your page and iFrame. In brief, send a message to instruct iFrame to update its localStorage, and another message to ask iFrame to return its localStorage content whenever you need the data you sent.

Be careful since:

  • This is a HTML5 API. Check if your app's minimum requirements allows the implementation.
  • This is a cross-origin communication, which means if other pages in your browser use postMessage, your iFrame will receive it too. You might need to add info into message to notice iFrame which message it should read.

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