当我开始学习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"]}背景.jschrome.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'));内容.jschrome.runtime.onMessage.addListener( function(message, sender, sendResponse) { document.body.style.backgroundColor = message.color; });
2 回答

慕盖茨4494581
TA贡献1850条经验 获得超11个赞
我以错误的方式使用以下函数。
旧代码:
document.getElementById('red').addEventListener('click', color('red'));
新代码:
document.getElementById('red').addEventListener('click', () => color('red'));
或
document.getElementById('red').addEventListener('click', fucntion() {color('red')});

四季花海
TA贡献1811条经验 获得超5个赞
尝试从回调中删除作为第一个参数。Tab
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
// your message logic
});
添加回答
举报
0/150
提交
取消