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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With