Reputation: 615
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?
Upvotes: 7
Views: 2076
Reputation: 10897
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);
Upvotes: 9