如何在 google chrome 扩展程序中获取页面的背景颜色?

How do I get the background color of a page in my google chrome extension?

我正在尝试编写一个简单的实验性 google 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});
}

现在,当我按下按钮一次时,它什么都不做,而当我第二次按下它时,无论我在哪个页面上,它都会将按钮颜色更改为灰色。我想知道我犯了什么错误以及我需要做什么才能使按钮按预期工作。提前感谢您提供的任何帮助

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

return一个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>.