Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run content script loop only when tab is active

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?

like image 935
Mark Avatar asked Feb 17 '16 08:02

Mark


1 Answers

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);
like image 169
Haibara Ai Avatar answered Sep 19 '22 23:09

Haibara Ai