【问题标题】:Chrome extension: Communication between content script and background.htmlChrome 扩展:内容脚本和 background.html 之间的通信
【发布时间】:2012-07-29 22:35:47
【问题描述】:

我是 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"
}

请帮忙!

【问题讨论】:

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


    【解决方案1】:

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

    如果你想支持 Chrome onRequest 和 sendRequest。否则,请使用*Message 方法。


    另外一个问题是你的函数位于后台页面,调用是在弹窗中进行的。这些是不同的作用域,如果你想从弹出窗口调用后台页面方法,请使用chrome.extension.getBackgroundPage()

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

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-28
    相关资源
    最近更新 更多