Chrome扩展程序消息从弹出窗口传递到内容

时间:2014-10-24 18:45:26

标签: google-chrome-extension callback

我正在尝试创建一个chrome扩展来学习前端技术,并且卡在弹出窗口和内容脚本之间的消息传递上。

以下是我要做的事情:  1.让背景页面保持全局变量。  2.当用户单击弹出html上的按钮时,将修改全局变量。同时,弹出窗口将全局var发送到所有选项卡的内容脚本。

在background.js中我有:

var settings = {
    version: 1,
    enabled: false
};

popup.js:

$(document).ready(function(){
    $("#switcher").click(function( event ) {
        event.preventDefault();

        var bg = chrome.extension.getBackgroundPage();
        var settings = bg.settings;
        settings.enabled = !settings.enabled;

        // send message to the content for all the tabs
        chrome.tabs.query({active: true}, function (tabs) {
            for (var i = 0; i < tabs.length; ++i) {
                console.log("sending message to tab " + i);
                chrome.runtime.sendMessage(tabs[i].id, {enabled: settings.enabled}, function(response) {
                    console.log(response);
                });
            }
        });
    });
});

最后,content.js:

$(document).ready(function(){
    chrome.runtime.onMessage.addListener(
        function (request, sender, sendResponse) {
            console.log("request is: " + request.enabled);

            sendResponse("get it");
        }
    );
});

我尝试调试它,但我发现'sendMessage'函数永远不会被返回..并且'onMessage'永远不会被触发。我错过了什么吗?

我的清单文件:

{
    "name": "__MSG_appName__",
    "version": "0.0.1",
    "manifest_version": 2,
    "description": "__MSG_appDescription__",
    "icons": {
        "16": "images/icon-16.png",
        "128": "images/icon-128.png"
    },
    "default_locale": "en",
    "permissions": [
        "contextMenus", "storage", "tabs"
    ],
    "background": {
        "scripts": [
            "scripts/background.js"
        ],
        "persistent": true
    },
    "browser_action": {
        "default_icon": {
            "19": "images/icon-19.png",
            "38": "images/icon-38.png"
        },
        "default_popup": "popup.html"
    },
    "content_scripts": [
        {
            "run_at":"document_start",
            "all_frames":true,
            "matches": ["*://*/*"],
            "js": ["bower_components/jquery/dist/jquery.min.js", "scripts/content.js"]
        }
    ],
    "web_accessible_resources": ["bower_components/jquery/dist/jquery.min.map"]
}

1 个答案:

答案 0 :(得分:3)

您应该使用chrome.tabs.sendMessage代替chrome.runtime.sendMessage向选项卡中的内容脚本发送消息。