'How do I get the background color of a page in my google chrome extension?
I'm trying to write a simple experimental google chrome extension that, on the press of a button, gets the background color of whatever page you are on and changes the color of the button to that color. E.g. if you are on a page with a black background, the color of the button changes to black when you press it.
I have written the following javascript code, where changeColor refers to the button in the html file
let changeColor = document.getElementById("changeColor");
function updateColor() {
chrome.storage.sync.get("color", ({ color }) => {
changeColor.style.backgroundColor = color;
});
}
updateColor()
changeColor.addEventListener("click", async () => {
let [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
chrome.scripting.executeScript({
target: { tabId: tab.id },
function: storePageBackgroundColor,
});
updateColor()
});
function storePageBackgroundColor() {
newColor = document.body.style.backgroundColor
chrome.storage.sync.set({"color": newColor});
}
now when I press the button once it does nothing and when I press it a second time it changes the buttons color to grey regardless of what page I'm on. I'd like to know what mistake(s) I have made and what I need to do to make the button work as intended. Thanks in advance for any help you can offer
Solution 1:[1]
The chrome API methods that return a Promise or can accept a callback are asynchronous, so the work is performed after the current synchronously running code completes, meaning that you're calling updateColor too early.
Note that you don't need storage for this task: simply pass the result via executeScript:
const changeColor = document.getElementById('changeColor');
changeColor.onclick = updateColor;
updateColor();
async function updateColor() {
const [tab] = await chrome.tabs.query({active: true, currentWindow: true});
const [{result}] = await chrome.scripting.executeScript({
target: {tabId: tab.id},
func: () => getComputedStyle(document.body).backgroundColor,
});
changeColor.style.backgroundColor = result;
}
Another possible problem is that your <script> tag is in <head>, so it runs before the button element is added to DOM. You can either move the script tag right before the closing </body> tag or add defer attribute e.g. <script src=popup.js defer></script>.
Solution 2:[2]
I don't have an answer , but if I were you , I would do this by initializing css considering it is the foundation of looks of the page. (a suggestion)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | wOxxOm |
| Solution 2 | Eldar Strakhanovich |
