Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
338 views
in Technique[技术] by (71.8m points)

javascript - 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);
question from:https://stackoverflow.com/questions/65546420/is-there-a-way-to-manually-unload-a-background-script-for-a-chrome-extension

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
    }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...