admin管理员组

文章数量:1391929

I am working on a chrome extension that uses content scripts to runs a loop. The tasks ran in the loop can consume quite some memory, and when having a lot of open tabs it impacts on the browser performance.

I am looking to run the loop only when the tab is active.

I am using onMessage.addListener my background page, then I can sendMessage from the content script and check the sender.tab.id against chrome.tabs.getSelected. But since sendMessage is asynchronous, I am forced to use setInterval for the "is tab active" check to update the variable that allows the loop to run or not.

Is there a better way to find if a tab is active from content scripts?

I am working on a chrome extension that uses content scripts to runs a loop. The tasks ran in the loop can consume quite some memory, and when having a lot of open tabs it impacts on the browser performance.

I am looking to run the loop only when the tab is active.

I am using onMessage.addListener my background page, then I can sendMessage from the content script and check the sender.tab.id against chrome.tabs.getSelected. But since sendMessage is asynchronous, I am forced to use setInterval for the "is tab active" check to update the variable that allows the loop to run or not.

Is there a better way to find if a tab is active from content scripts?

Share Improve this question asked Feb 17, 2016 at 8:22 MarkMark 6151 gold badge9 silver badges31 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 9

Take a look at Page Visibility API, I think check

if (document.visibilityState === "hidden")

can solve your problem.

And I'm not sure what you did in the loop, if just to detect tab state, you can also use visibilitychange event listener instead.

document.addEventListener("visibilitychange", function () {
  if (document.hidden) {
    //...
  }
}, false);

本文标签: javascriptRun content script loop only when tab is activeStack Overflow