在事件回调中访问iFrame的localStorage? [英] Accessing localStorage of an iFrame in an event callback?

查看:512
本文介绍了在事件回调中访问iFrame的localStorage?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对localStorage作弊.规范定义,当localStorage中的值更改时,同一域上的所有其他打开的页面均会收到 storage 事件回调.我还希望该事件在更改了值的页面上触发.

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.

我向每个页面添加了一个隐藏的iFrame,该页面从同一域加载空文档,并尝试将其用作localStorage更改的目标(因此,从技术上讲,我正在查看的页面不是localStorage的来源更改)

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 已成功存储,并且所有窗口均收到 storage 事件.当我单击播放音频时,在回调中出现以下错误-未捕获的DOMException:无法在存储"上执行"setItem":拒绝对此文档进行访问.

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

更新:我不知道我在上面的示例中是否做错了什么,但是代码似乎可以在 some 回调中使用.我在页面上有一个带有点击事件的锚点,我可以在其中可以通过iFrame设置localStorage

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

推荐答案

您可以尝试 postMessage API ,以启用页面和iFrame之间的通信.简而言之,发送一条消息以指示iFrame更新其localStorage,并发送一条消息以要求iFrame在需要发送数据时返回其localStorage内容.

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.

要小心,因为:

  • 这是HTML5 API.检查您的应用程序的最低要求是否允许实施.
  • 这是跨域通信,这意味着如果浏览器中的其他页面使用postMessage,则iFrame也将收到它.您可能需要在消息中添加信息,以通知iFrame它应读取哪条消息.

这篇关于在事件回调中访问iFrame的localStorage?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆