【问题标题】:Permission denied to call method ChromeWindow.postMessage for iframe inside XUL page在 XUL 页面内为 iframe 调用方法 ChromeWindow.postMessage 的权限被拒绝
【发布时间】:2013-01-11 21:19:11
【问题描述】:

我有一个扩展,里面有一个 XUL 文件(我们称之为 A)。 XUL 文件包含一个<iframe>,其中加载了一些网页(我们称之为B)。 B 是从不同的域加载的。
A 是 B 的父母。我想使用 window.parent.postMessage() 从 B 内部向 A 发送消息。 我收到以下异常:

... 拒绝 B 调用方法 ChromeWindow.postMessage

如何修复该错误?如果没有办法做到这一点,我该如何将消息从 B 传递给 A?

我在 Windows 7 下使用 Firefox 16.0.1。

【问题讨论】:

  • @Wladimir Palant,这里是 Firefox 问题,与 FF 扩展开发有关,与您的“可能重复”链接中的 XMLHttpRequest 无关。问题是为了postMessage 到某个窗口,应该调用<some window>.postMessage(...),在我的情况下,some windowwindow.parent。所以,window.parent.postMessage() 应该可以工作,但它没有,这使得 postMessage() 无法用于窗口之间的通信。

标签: javascript firefox firefox-addon cross-domain xul


【解决方案1】:

我有一个非常相似的问题, 只是我有一个无法将“postMessage”发送到我的 xul-background-task 的 html-popup(本地)。 我想我得到它的工作, 奇怪的是,通过启动我自己的 MessageEvent (与 postMessage 完全相同) 但是有一个(我认为已经过时的)后备……简而言之:我从 MDN 和其他网站一起酿造了一些东西;)

内容中我的脚本:

var Communicator = 
{
    postMessage: function(data) 
    { 
        // We need some element to attach the event to, since "window" wont work
        // let's just use a fallback JSON-stringified textnode
        var request = document.createTextNode(JSON.stringify(data));
        // and as always attach it to the current contentwindow
        document.head.appendChild(request);
        // Now let's make a MessageEvent of our own, just like window.postMessage would do
        var event = document.createEvent("MessageEvent");
        event.initMessageEvent ("own_message", true, false, data, window.location, 0, window, null);
        // you might want to change "own_message" back to "message" or whatever you like
        //and there we go
        request.dispatchEvent(event);
    }
}

现在使用 Communicator.postMessage(data) 代替 window.postMessage(data) 就这样! 现在,在我的叠加层中,除了我们的好老人,什么都没有

addEventListener('own_message', someMessageFunc, false, true);
//or maybe even "message" just like originally

希望这对你也有用(没有在 iframe 上检查...)

【讨论】:

  • 我也使用过类似的方法。创建事件绝对有效,请参阅下面的答案。很高兴 SO 社区有一个成员,这真的很有帮助。为此标记为正确。但我仍然不清楚,为什么 postMessage 不起作用?做不到这种情况需要什么?
  • 我猜不是 postMessage 失败了,而是目标对象不可用。据我所知,firefox 试图将它的 browser.xul 隐藏在尽可能远离内容脚本的地方,以避免恶意交互;这就是为什么您不能从任何内容窗口(我不知道)将 postMessage 附加到 browser.xul(在您的情况下为 window.parent),因此我们必须创建一个目标,contentwindow 和 backgroundscript 都可以与之交互,并且我的 Communicator 对象在这里插入。
【解决方案2】:

你应该检查type of iframe B

编辑:

显然您必须将您的 chrome 标记为 contentaccessible,并考虑到安全性。

【讨论】:

  • 我试过了!它设置为chrome,我仍然得到permission denied。我也试过 type='content' 并得到同样的错误。
  • 我在我的 chrome.manifest 文件中也尝试了 contentaccessible=yes 并得到了同样的错误。
【解决方案3】:

只是发帖以防有人遇到同样的问题。
使用 here 描述的事件成功从 B 内部向 A 发布消息。

但这不是答案,因为window.parent.postMessage() 仍然无法按预期工作。

【讨论】:

    猜你喜欢
    • 2011-08-04
    • 2010-10-28
    • 2011-04-22
    • 2015-07-20
    • 1970-01-01
    • 2016-09-24
    • 2014-03-31
    • 2014-06-20
    • 2017-08-09
    相关资源
    最近更新 更多