【问题标题】:Communication between created Iframe and extension, google chrome extension创建的 iframe 与扩展、谷歌浏览器扩展之间的通信
【发布时间】:2017-09-08 14:09:07
【问题描述】:

我尝试将消息从从我的扩展加载的 iframe 发送到我的扩展(背景脚本或内容脚本)。 创建的 Iframe 通过内容脚本从扩展加载。 我正在寻找一种交流方式,但我所有的尝试都失败了......

Manifest.json

{
"author": "***********",
"background": {
    "page": "back/background.html",
    "persistent": true
},
"browser_action": {
    "default_title": "***",
    "default_popup": "./popup/popup.html"
},
"content_scripts": [
    {
        "matches": ["<all_urls>"],
        "js": ["./content/allurls.js"],
        "all_frames":true
    },
    {
        "matches": ["<all_urls>"],
        "js": ["./banner/confirm_banner.js"]
    }
],
"web_accessible_resources": [
    "frame.html"
],
"description": "oui",
"manifest_version": 2,
"name": "***",
"permissions": ["tabs"],
"version": "1.0"
}

Confirm_banner.js(加载 iframe)

var extensionOrigin = 'chrome-extension://' + chrome.runtime.id;

window.onload = load_iframe();

function load_iframe()
{
if (!location.ancestorOrigins.contains(extensionOrigin)) 
{
    var iframe = document.createElement('iframe');
    iframe.src = chrome.runtime.getURL('../frame.html');
    iframe.style.cssText = 'position:fixed;top:0;left:0;display:block;' +
                           'width:100%;height:40px;';
    document.body.appendChild(iframe);
}
}

Frame.js(与 frame.html 链接的脚本)

$(document).ready(function()
{
    $('#jamais').click(function()
    {
        send_message("BANNER", "jamais");
        alert("send");
    });
});

function send_message(type, data)
{
    var msg = {
        type: type,
        data: data
    };
    window.postMessage(msg, "*");
}

allurls.js 中的处理程序(内容脚本)

window.addEventListener('message', function(event) {
    if (event.data.type && (event.data.type === 'BANNER'))
    {
        alert("ouimonsieur");
    }
});

因此,来自 iframe.js 的消息发送良好(由警报证明),但内容脚本没有收到任何消息,甚至在 :

if (event.data.type && (event.data.type === 'BANNER'))

有人可以看到什么是错误的或我可以使用哪些其他消息传递协议(我也尝试过使用 top.window.postmessage)?

【问题讨论】:

  • iframe 中的 window 指的是 iframe 的窗口。您需要发送到parent
  • 嗯,好的,我会尝试,但是内容脚本应该进入页面中的所有 iframe,所以我仍然不明白为什么它不起作用。
  • Frame.js 不是内容脚本,它是 iframe 脚本并在扩展程序的上下文中运行。
  • 好的,我用 parent.postmessage 替换了 window.postmessage,它运行良好,谢谢。要发布答案以便我验证吗?

标签: javascript iframe google-chrome-extension


【解决方案1】:

答案是 wOxxOm,我很接近:

只需在frame.js 中将window 替换为parent 即可,一切正常。

因为即使内容脚本在 iframe 中运行,

Frame.js 不是内容脚本,它是 iframe 脚本并在扩展程序的上下文中运行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-17
    • 2014-07-24
    • 2016-06-08
    • 2012-04-21
    • 1970-01-01
    相关资源
    最近更新 更多