设置chrome超时,脚本,执行脚本

1hdlvixo  于 2022-12-06  发布在  Go
关注(0)|答案(2)|浏览(253)

我试图设置超时到我的扩展弹出窗口。我看到工作完成后,它不会自动关闭,直到点击页面上的某处。我试图设置超时自动关闭我的扩展弹出窗口。下面是我的代码。

a.addEventListener("click", async () => {
 button.style.backgroundColor = 'white';
  document.getElementById("button").style.backgroundColor = 'white';
   chrome.scripting.executeScript({
     target: { tabId: tab.id },
     func: codeWork,
   });
});

我遵循了许多可用的建议,但它抛出了Uncaught EvalError: Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in Content Security Pol中显示的错误
请帮助我如何设置我的弹出功能计时器。
还有我的func:codeWork返回响应。响应可能包含错误。我想根据响应更改按钮的颜色。如何做到这一点?任何帮助都非常感谢!!!

qni6mghb

qni6mghb1#

这是第一个问题的答案。此示例弹出窗口将在10秒后自动关闭。
popup.js

const elmCounter = document.getElementById("counter");

counter();

async function counter() {
  for (let i = 0; i < 10; i++) {
    elmCounter.innerText = i;
    await new Promise(r => setTimeout(r, 1000));
  }
  window.close();
}

popup.html

<!DOCTYPE html>
<html>

<body>
  <div id="counter">
    <script src="popup.js"></script>
</body>

</html>

manifest.json

{
  "name": "hoge",
  "version": "1.0",
  "manifest_version": 3,
  "action": {
    "default_popup": "popup.html"
  }
}
t3psigkw

t3psigkw2#

这是第二个问题的答案。
popup.js

const elmExec = document.getElementById("exec");

elmExec.onclick = async () => {
  const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
  await chrome.scripting.executeScript({
    target: { tabId: tabs[0].id },
    func: func
  });
}

const func = () => {
  const color = ["red", "blue", "green"];

  const getRandomInt = (max) => {
    return Math.floor(Math.random() * max);
  }

  chrome.runtime.sendMessage({ color: color[getRandomInt(3)] });
}

chrome.runtime.onMessage.addListener((message) => {
  elmExec.style.backgroundColor = message.color;
});

popup.html

<!DOCTYPE html>
<html>

<body>
  <div id="counter">
    <input type="button" id="exec" value="exec">
    <script src="popup.js"></script>
</body>

</html>

manifest.json

{
  "name": "hogehoge",
  "version": "1.0",
  "manifest_version": 3,
  "permissions": [
    "activeTab",
    "scripting"
  ],
  "action": {
    "default_popup": "popup.html"
  }
}

相关问题