从选项页面发送消息到内容脚本

时间:2018-04-02 15:17:06

标签: javascript google-chrome-extension

在chrome文档中,我们可以使用以下命令从选项页面发送消息:

chrome.runtime.sendMessage

我们不能使用:

chrome.tabs.sendMessage

我想从选项页面向内容脚本发送消息。我可以直接这样做吗? 这是我的选项页面脚本:

document.addEventListener("DOMContentLoaded", function() {
    var radio = document.querySelectorAll("input[type=radio][name=quality]");
    for(i=0; i<radio.length; i++)
    radio[i].addEventListener("change", function(){
        val = this.id;
        localStorage.setItem("youtube_filter_video_quality", val);
        chrome.runtime.sendMessage({"youtube_filter_video_quality": val});
    });
});

这是内容脚本:

    chrome.runtime.onMessage.addListener(
        function(request, sender, sendResponse) {
            if(request.youtube_filter_video_quality!==undefined){
                console.log(request.youtube_filter_video_quality);
            }
        }
    );

这是manifest.json:

{
    "name": "__MSG_name__",
    "short_name": "__MSG_short_name__",
    "manifest_version": 2,
    "version":"1.5.0.0",
    "description": "__MSG_description__",
    "default_locale": "en",
    "browser_action": {
        "default_icon": "48.png",
        "default_title": "__MSG_default_title__",
        "default_popup": "popup.html"
    },
    "background":{
        "page":"background.html",
        "persistent": false
    },
    "content_scripts":[
    {
        "matches": [ "*://*.youtube.com/*" ],
        "css": ["app_player.css"],
        "run_at": "document_end"
    }
    ],
    "permissions": [
        "tabs",
        "activeTab",
        "storage",
        "<all_urls>",
        "webNavigation"
    ],
    "icons": {
            "64":"64.png",
            "48": "48.png",
            "32":"32.png",
            "16": "16.png",
            "128": "128.png"
    },
    "options_page": "options.html",
    "options_ui": {
        "chrome_style": true,
        "page": "option.html"
    }
}

console.log无法写任何内容(空白)。

0 个答案:

没有答案