浏览器中打开的Chrome扩展程序页面是否可以与后台页面通信?

时间:2015-08-25 12:02:48

标签: google-chrome-extension

我的一个扩展html页面,在浏览器中打开时需要与后台脚本进行通信。我尝试过提及here的方法,但无法从页面向后台发送消息。我该怎么做?我不能在以chrome-extension://namhfjepbaaecpmpgehfppgnhhgaflne/content/web/viewer.html之类的内容开头的页面上有内容脚本,因此无法使用传统的消息传递

1 个答案:

答案 0 :(得分:3)

您的问题中提到的链接适用于扩展程序包之外的普通网页。

如果显示的html文件属于您的扩展包,则可以使用页面脚本文件中manifest.json允许的所有chrome API。

例如,要将消息发送到后台/活动页面,请使用chrome.runtime.sendMessage

  • options.js,从options.html链接

    for label, vals in d.iteritems():  # use d.items() in python 3
        do_something_with label and vals
    
  • 背景/活动页面

    chrome.runtime.sendMessage({text: "Hello"}, function(response) {
        console.log(response);
    });
    

或者,您可以直接访问背景页面:

  • 持久性背景页

    chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
        if (message.text == "Hello") {
            sendResponse({text: "Got it"});
        }
    });
    
  • event page

    chrome.extension.getBackgroundPage().someGlobalFunction()
    

对于内容脚本,您可以通过在html文件中手动引用来直接添加它们:

chrome.runtime.getBackgroundPage(function(bg) {
    bg.someGlobalFunction();
});