从内容脚本中的后台和弹出窗口接收消息

时间:2015-07-21 11:48:47

标签: javascript dom google-chrome-extension

我在接收来自background.js和popup.js的邮件时遇到了麻烦。我想在弹出窗口中单击按钮时访问activeTab DOM内容。这是 manifest.json

部分
    ...
"background": {
    "scripts":    ["background.js"],
    "persistent": false
},
"content_scripts": [
    {
        "matches": ["<all_urls>"],
        "js":      ["content.js"]
    }
],
"permissions": [
    "tabs",
    "activeTab",
    "<all_urls>"
]

我从 popup.js 向背景(以及内容scrpit)发送消息:

document.addEventListener('DOMContentLoaded', function() {
    document.getElementById("start_button").onclick = function() {

        chrome.tabs.query({active:true, currentWindow: true}, function(tabs){
            chrome.tabs.sendMessage(tabs[0].id, {
                type: "start",
                text: "task from popup to content"
            });
    });
});

但是我无法在 content.js 中接收来自后台和弹出窗口的消息:

function get_stuff_from_page(text) {
    alert('recieved IN content:' + text);

    var blocks_number = document.getElementsByTagName('div').length;
    //how do i pass it back to background?
}

//i try to recieve it here and it doesn't work
chrome.extension.onMessage.addListener(function(message, sender, sendResponse) {
    switch (message.type) {
        case "start":
            alert('recieved message 1');
            get_stuff_from_page(message.text);
        break;
    }
});

//also doesn't work here
chrome.runtime.onMessage.addListener( function(message, sender, sendResponse) {
    switch (message.type) {
        case "start":
            alert('recieved message 2');
            get_stuff_from_page(message.text);
    }
});

接收消息(甚至发送消息)时我的错在哪里?我真的很困惑,因为我尝试了大多数方法,但没有任何作用。 还有我如何将页面的DOM传递回后台?提前谢谢!

UPD :建议的答案(Popup script and content script can't communicate?)似乎对我不起作用。也许我错过了一些全球性的东西?

0 个答案:

没有答案