Home > Enterprise >  setTimeout to chrome.scripting.executeScript
setTimeout to chrome.scripting.executeScript

Time:10-23

I was trying to set Timeout to my extension popup .I see after the work is done, it doesn't get automatically closed until clicked on somewhere on the page. I was trying to set timeout for auto closing of my extension popup. Below is my code.

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

I followed many suggestions available but it is throwing the error shown in Uncaught EvalError: Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in Content Security Pol

Please help me on how to set timer to my popup function.

Also my func:codeWork return response. The response might contain error. I want to change the color of the button based on the response . How to do that ? Any help is really appreciated!!!!

CodePudding user response:

This is the answer to the first question. This sample popup will automatically close after 10 seconds.

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"
  }
}

CodePudding user response:

This is the answer to the second question.

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"
  }
}
  • Related