我如何在我的谷歌chrome扩展页面的背景颜色?



我试图写一个简单的实验性谷歌chrome扩展,在按下一个按钮,得到你所处的任何页面的背景颜色,并将按钮的颜色更改为该颜色。例如,如果你在一个黑色背景的页面上,当你按下它时,按钮的颜色就会变成黑色。

我写了下面的javascript代码,其中changeColor指的是html文件

中的按钮
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});
}

现在,当我按下按钮一次它什么也不做,当我按它第二次它改变按钮的颜色为灰色,不管我在什么页面上。我想知道我犯了什么错误,我需要做什么才能使按钮按预期工作。提前感谢您提供的任何帮助

返回Promise或可以接受回调的chromeAPI方法是异步的,因此工作是在当前同步运行的代码完成后执行的,这意味着您过早地调用updateColor

请注意,此任务不需要存储空间:只需通过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;
}

另一个可能的问题是您的<script>标签在<head>中,因此它在按钮元素添加到DOM之前运行。您可以将脚本标签移动到关闭</body>标签之前,或者添加defer属性,例如<script src=popup.js defer></script>.

我没有答案,但如果我是你,我会通过初始化css来解决这个问题,因为它是页面外观的基础。(建议)

最新更新