简体   繁体   中英

Is there a way to manually unload a background script for a chrome extension?

I am developing a Chrome extension that tracks how long you have been using your computer. I increment using an interval, and am checking if the computer is locked using chrome.idle.queryState, and if it is locked I don't change my counter.

Is there a way to manually unload a background page, rather than constantly checking with an interval? Or does the background script ever unload and reload automatically, like after the computer is sleeping for X minutes? Since I have an interval, I wonder if the script will ever unload on its own. I do something similar to this:

setInterval(function () {
    chrome.idle.queryState(15, function (state) {
        if (state !== "locked") {
            counter += 1;
            console.log(counter);
        }
    }
}, 6000);

Thanks to wOxxOm and Nadia Chibrikova for answering the question. In unloading the script, it is best to use a non-persistent background script, like so:

...
"background": {
    "scripts": ["background.js"],
    "persistent": false
},
...

This would unload after 15-30 seconds regardless of any intervals, as long as there are no open message ports and you don't inspect it in devtools. For my purposes, I am keeping a message port open, so I use a variable to keep track of whether Chrome is idle or not by using chrome.idle.onStateChanged, and modified my code accordingly, with this:

chrome.idle.setDetectionInterval(15);
chrome.idle.onStateChanged.addListener(function (state) {
    if (state === "locked") {
        isLocked = true;
    } else {
        isLocked = false;
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM