当我开始学习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;
}
);
慕盖茨4494581
四季花海
相关分类