javascript - Chrome 扩展 : Communication between content script and background. html

标签 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>

list .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"
}

请帮忙!

最佳答案

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

如果你想支持 Chrome <20(很多 Ubuntu 用户还在 Chromium 18,因为 PPA 没有更新),使用 onRequestsendRequest。否则,使用 *Message 方法。


还有一个问题就是你的函数位于后台页面,在弹窗中调用。这些是不同的范围,如果你想从弹出窗口调用后台页面方法,使用 chrome.extension.getBackgroundPage() :

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

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

关于javascript - Chrome 扩展 : Communication between content script and background. html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11752341/

相关文章:

google-chrome-extension - 在元素面板中聚焦项目的 Chrome 扩展

javascript - Firefox/Chrome Web 扩展 - 尝试通过内容脚本注入(inject) IFrame 时出现安全错误

javascript - 通过 Google Chrome 扩展程序中的内容脚本从 DOM 元素中删除 "onmousedown"事件

javascript - 验证表单 hasError AngularJS

firebase - 如何跨多个位置同步 Firebase 用户? (扩展名+网站)

javascript - 根据文本高度为每个 div 实例提供带有 jquery 的特定 css

java - 为什么我需要在批处理文件中提及绝对地址?

javascript - 如何将消息发布到 iFrame 中?

javascript - 在 Webpack/Sass 构建中修复 "Cannot read property ' toStringTag' of undefined"

javascript - 组件中的 angularjs 'bindings' 不起作用