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
localstorage is a property of the domain So on the parent, the execution window page is from fiddle.jshell.net and the iframe is from jsfiddle.net , as per your hardcoded iframe src - they are different domains and can't access each other's localstrage.
There are four basic JavaScript methods you can use to access and work with localStorage: setItem() - takes a key-value pair and adds it to localStorage. getItem() - takes a key and returns the corresponding value. removeItem() - takes a key and removes the corresponding key-value pair.
You can only read the cookie of the iframe within the same iframe only and after reading you can pass the cookie value to the parent window using the postMessage.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With