chrome.tabs.query 未将消息传递到内容.js

当我开始学习chrome扩展时,我被困在一个基本程序中。我的程序是构建一个扩展,该扩展具有更改网页颜色的按钮。更改颜色应该是操作驱动的,这就是为什么我没有使用默认css在页面加载时更改颜色的原因。以下是我的文件。我遇到的问题是后台的chrome.tabs.query.js没有返回tabs数组,我得到“ID未引用错误”任何帮助都是值得赞赏的。我已经在谷歌和StackOverflow上搜索了n篇文章,但没有什么可以帮助我


Files: manifest.json


    {

"manifest_version": 2,

"name": "Hello world",

"description": "Demo extension",

 "version": "1.0",


 "icons":

{

"16": "images/dog.png", 

"48": "images/dog.png",

"128": "images/dog.png"

},


"background": {

        "persistent": false,

        "scripts": ["background.js"]

    },


"browser_action":

{

"default_icon": "images/dog.png",

"default_popup": "popup.html"

},


"content_scripts": [{

    "js": ["content.js"],

    "matches": ["<all_urls>"]

  }],


"permissions": ["tabs", "http://*/*","activeTab"]

}

背景.js


chrome.runtime.onMessage.addListener(

    function(message, sender, sendResponse) {

        switch(message.type) {

            case "setcolor":

                chrome.tabs.query({active: true, currentWindow: true}, function(tab){

                chrome.tabs.sendMessage(tab[0].id,{type: "setcolor",color: message.color})

                });

                break;

            default:

                console.error("Unrecognised message: ", message);

        }


弹出窗口.html


<!DOCTYPE html>

<html>

<head>


</head>

<body>



<p id="demo">Click below button to change color of page</p>


<button type="button" id = "red"> RED </button>

<script src = "myscript.js"></script>


</body>

</html> 

myscript.js(或弹出窗口.js)


function color(colorval) {

    chrome.runtime.sendMessage({type: "setcolor",color: colorval})

}


document.getElementById('red').addEventListener('click', color('red'));

内容.js


chrome.runtime.onMessage.addListener(

    function(message, sender, sendResponse) {

        document.body.style.backgroundColor = message.color;

        }

);


HUX布斯
浏览 186回答 2
2回答

慕盖茨4494581

我以错误的方式使用以下函数。旧代码:document.getElementById('red').addEventListener('click',&nbsp;color('red'));新代码:document.getElementById('red').addEventListener('click',&nbsp;()&nbsp;=>&nbsp;color('red'));或document.getElementById('red').addEventListener('click',&nbsp;fucntion()&nbsp;{color('red')});

四季花海

尝试从回调中删除作为第一个参数。Tabchrome.tabs.query({active: true, currentWindow: true}, function(tabs){&nbsp; &nbsp;// your message logic});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript