无法在Chrome扩展程序中找到DOM元素

时间:2015-10-30 05:17:54

标签: javascript google-chrome-extension

我是Chrome扩展程序开发的新手,我从简单的要求开始,在Chrome扩展程序中单击按钮将更改当前选项卡中所有DIV的颜色。

的manifest.json

 {
        "name": "BrowserExtension",
        "version": "0.0.1",
        "manifest_version": 2,
        "description" : "Description ...",
        "browser_action": {
            "default_icon": "icon.png",
            "default_title": "That's the tool tip",
            "default_popup": "popup.html"
        },
        "background": {
            "scripts": ["background.js"],
            "persistent": false
        },
        "content_scripts": [{
            "matches": ["<all_urls>"],
            "js": ["content.js"]
        }]
    }

popup.html

  <script type="text/javascript" src="popup.js"></script>
        <div style="width:200px">
            <button id="button">Color all the divs</button>
        </div>

popup.js

window.onload = function() {
    document.getElementById("button").onclick = function () {
        chrome.extension.sendMessage({
            type: "color-divs"
        });
    }
}

background.js

// listening for an event / one-time requests
// coming from the popup
chrome.extension.onMessage.addListener(function (request, sender, sendResponse) {
    switch (request.type) {
        case "color-divs":
            alert('on mesg');
            colorDivs();
            break;
    }
    return true;
});

// send a message to the content script
var colorDivs = function () {
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
        var tab = tabs[0];
        alert("tabs[0] " + tab.id);
        chrome.tabs.sendMessage(tab.id, { type: "colors-div" }, function (response) {
            alert("response: " + response);
            chrome.browserAction.setBadgeText({ text: "red!" });
        });

    });
}

content.js

chrome.extension.onMessage.addListener(function(message, sender, sendResponse) {
    alert('recieve msg' + message);
    switch (message.type) {
        case "colors-div":
            console.log('color message');
            var divs = document.querySelectorAll("div");
            if(divs.length === 0) {
                alert("There are no any divs in the page.");
            } else {
                for(var i=0; i< divs.length; i++) {
                    divs[i].style.backgroundColor = message.color;
                }
            }
        break;
    }
});

我陷入Content.js,我无法收到background.js发送的邮件。

请帮助我找到解决方案,我可以通过按钮点击background.js onMessage然后转到content.js onMessage来接收消息。

0 个答案:

没有答案