Chrome扩展程序:内容脚本和background.html之间的通信

时间:2012-08-01 03:53:22

标签: javascript google-chrome-extension content-script

我是Chrome扩展新手。我正在尝试在内容脚本和 background.html 页面之间进行通信。 background.html 向内容脚本发送请求“ hello ”,内容脚本应以“ hello background ”警告回复。但它只是没有发生。我的 background.html 代码是:

function testRequest() {        
    chrome.tabs.getSelected(null, function(tab) {
        chrome.tabs.sendRequest(tab.id, {greeting: "hello"});
    });    
}

content.js 代码:

chrome.extension.onMessage.addListener(
    function(request, sender, sendResponse) {
        if (request.greeting == "hello")
        alert("hello background");
    }
);

popup.html 代码:

<!doctype html>
<html>
    <head></head>
    <body>
        <form>
            <input type="button" value="sendMessage" onclick="testRequest()" />
        </form>    
    </body>
</html>

的manifest.json

{
    "browser_action": {
        "default_icon": "icon.png",
        "popup": "popup.html"
    },
    "background": {
        "page": "background.html"
    },
    "permissions": [
        "tabs",
        "http://*/*",
        "https://*/*",
        "notifications",
        "contextMenus"
    ],
    "content_scripts": [
        {
            "matches": ["http://*/*","https://*/*"],
            "js": ["content.js"]
        }
    ],
    "name": "FirstExtension",
    "version": "1.0"
}

请帮忙!

1 个答案:

答案 0 :(得分:22)

在Chrome 20中,{p> sendRequest / onRequest已替换为sendMessage / onMessage*Message不仅仅是*Request的别名,它是一个不同的API。

如果您想支持Chrome&lt; 20(许多Ubuntu用户仍在Chromium 18,因为PPA未更新),请使用onRequestsendRequest。否则,请使用*Message方法。


另一个问题是您的功能位于后台页面,并且在弹出窗口中进行调用。这些是不同的范围,如果要从弹出窗口调用背景页面方法,请使用chrome.extension.getBackgroundPage()

chrome.extension.getBackgroundPage().testRequest();

最后说明:您使用的是清单版本1和内联事件处理程序。不推荐使用此做法,有关详细信息,请参阅http://code.google.com/chrome/extensions/manifestVersion.html

相关问题