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

Cha*_*eep 16 javascript google-chrome-extension content-script

我是Chrome扩展新手.我正在尝试在内容脚本和background.html页面之间进行通信.该background.html发送一个请求," 你好 ",以内容脚本和内容脚本应该以"进行回应你好背景 "警报.但它只是没有发生.我的background.html代码是:

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

content.js代码:

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

popup.html代码:

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

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"
}
Run Code Online (Sandbox Code Playgroud)

请帮忙!

Rob*_*b W 23

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

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


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

chrome.extension.getBackgroundPage().testRequest();
Run Code Online (Sandbox Code Playgroud)

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