【问题标题】:Send a message to background script from iframe within a popup在弹出窗口中从 iframe 向后台脚本发送消息
【发布时间】:2014-10-06 09:43:18
【问题描述】:

我有一个 google chrome 扩展程序,它具有包含 iframe 的弹出窗口。 iframe 指向域 abc.com。有什么方法可以单击 iframe 并向我的 chrome 扩展的后台脚本发送消息。我尝试将以下 javascript 代码添加到我在 abc.com 上的 index.php 页面中。

<script src="http://code.jquery.com/jquery-1.11.1.min.js" type="text/javascript"   charset="utf-8"></script>
<script type="text/javascript" charset="utf-8">
    $(document).ready(function(){
        $("#mybtn").click(function(){
            chrome.extension.sendMessage({ action: "new message" });
        });
    });
</script>

在 background.js 中

chrome.extension.onMessage.addListener(function(request,sender,sendResponse(){
     if(request.action=="new message"){
        alert ("Message Recieved");
     }
});

但它不起作用,也许我错过了一些东西。请帮忙。

【问题讨论】:

    标签: javascript jquery iframe google-chrome-extension


    【解决方案1】:

    iframe 中,您不再处于扩展页面上下文中。因此,扩展 API 不会暴露给在 abc.com 上运行的脚本。

    但是,由于它是一个扩展和一个你都控制的域,你可以在它们之间建立External Messaging

    第一步:Acquire a permanent ID for your extension.

    第 2 步:在扩展程序的清单中声明您希望 abc.com 能够与您交谈:

    "externally_connectable": {
      "matches": ["*://*.abc.com/*"]
    }
    

    第 3 步:在 abc.com 上,如果安装了扩展程序,您将暴露 chrome.runtime.sendMessage

    // on the website
    if(chrome && chrome.runtime && chrome.runtime.sendMessage){
      /* At least one extension is ready to listen */
    } else {
      /* Not Chrome, or extension is not installed */
    }
    

    第 4 步:使用第一步中的 ID 发送消息:

    var extensionId = "abcdefghijklmnoabcdefhijklmnoabc";
    chrome.runtime.sendMessage(extensionId, { action: "new message" });
    

    第五步:在后台页面,接收消息:

    chrome.runtime.onMessageExternal.addListener(
      function(request,sender,sendResponse) {
        if(request.action=="new message"){
          alert ("Message Recieved");
        }
      }
    );
    

    附:请注意chrome.extension.sendMessage 和朋友已弃用chrome.runtime.sendMessage

    【讨论】:

    • 我可以使用相同的方法将消息发送回 iframe 吗??
    • 基本我想在指向 abc.com 的 iframe 和我的扩展程序的后台脚本之间设置双向通信
    • 否;页面必须启动连接。如果需要回复消息,可以使用sendResponse;如果你需要完整的双向通信,iframe 应该打开一个带有chrome.runtime.connect 的端口。请参阅我链接的消息传递文档。
    • 请注意,如果您的弹出窗口关闭,iframe 将被破坏并且连接将被切断。如果您需要长期连接,请考虑在后台页面中使用 iframe,或者更好 - WebSockets。
    猜你喜欢
    • 1970-01-01
    • 2014-11-23
    • 2020-10-12
    • 2017-12-24
    • 1970-01-01
    • 2023-01-16
    • 2017-02-15
    • 2013-10-12
    • 1970-01-01
    相关资源
    最近更新 更多