Chrome扩展消息传递-如何传递HTML

Chrome Extension Message Passing - How to pass HTML

本文关键字:何传递 HTML 扩展 消息传递 Chrome      更新时间:2023-09-26

我正试图从chrome扩展中的本地向活动选项卡上的div发送HTML。我通过后台脚本发送HTML,并通过注入活动选项卡的内容脚本接收。

我已经让端口工作起来,并用各种简单的基于文本的消息进行了测试。div也出现了,但它是空白的,因为HTML没有正确发送。有人知道我的代码出了什么问题吗?

后台脚本:

chrome.runtime.onConnect.addListener(function(port) {
    console.assert(port.name == "sidebar");
    port.onMessage.addListener(function(msg) {
        if (msg.command == "read_sidebar")
        {
            //var sidebarURL = chrome.extension.getURL("sidebar.html");
            //console.log(sidebarURL);
            var element = document.createElement('div');
            element.id = "test";
            $("test").load('sidebar.html');
            port.postMessage({command: "load_sidebar", html: element.innerHTML})
        } 
        else if (msg.command == "close_load") {
            console.log("told to close load");
        } 
    });
});

内容脚本:

function loadSidebar() {
    var port = chrome.runtime.connect({name: "sidebar"});
    port.postMessage({command: "read_sidebar"});
    port.onMessage.addListener(function(msg) {
        if (msg.command == "load_sidebar")
        {
            console.log(msg.html);
            document.getElementById("mySidebar").innerHTML= msg.html;
            port.postMessage({command: "close_load"});
        }
    });
}

此API只能发送JSON-可序列化对象,而HTMLElement不可序列化。

您可以尝试将HTML添加到清单的web_accessible_resources部分:

  "web_accessible_resources" : [
    "sidebar.html",
    (any resources used by sidebar.html)
  ],

然后,您可以使用直接从内容脚本加载文件

chrome.runtime.getURL('sidebar.html')

作为其URL。

您可以将它作为iframe注入,或者如果它是静态HTML,您可以使用XHR请求它并处理响应。

相关文章: