I am stuck in a basic program just when I started learning chrome extension. My program is to build an extension which has button to change the color of the webpage. Changing color should be action driven that is why I didn't use default css to change the color on page load. Below are my files. The problem that I have is chrome.tabs.query in background.js is not returning tabs array and I get "ID not referenced error" Any help is appreciated. I have searched n number of articles on google and StackOverflow but nothing is helping me
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"]
}
background.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);
}
popup.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 (or popup.js)
function color(colorval) {
chrome.runtime.sendMessage({type: "setcolor",color: colorval})
}
document.getElementById('red').addEventListener('click', color('red'));
content.js
chrome.runtime.onMessage.addListener(
function(message, sender, sendResponse) {
document.body.style.backgroundColor = message.color;
}
);