I have an extension that needs to detect when a new Chrome session has started. I found a post here that suggested the following:
chrome.runtime.onStartup.addListener(async function() {
console.log("new startup detected");
await chrome.storage.local.set({"status":false});
});
However, it seems that the listener does not work. It is also not clear what startup it refers to. Start up of Chrome or startup of the extension. Can someone clarify how to detect when a new chrome has started? TIA.
Updated Code
chrome.windows.onCreated.addListener(async function() {
console.log("new startup detected");
await chrome.storage.local.set({"status":false});
});
Updated withj Manifest
{
"manifest_version": 3,
"name": "Auto_Select",
"description": "This extension auto selects Mturk HITs",
"version": "1.0.12",
"action": {
"default_icon": "auto_select.png",
"type": "module",
"default_popup": "auto_select.html"
},
"permissions": [
"tabs",
"activeTab",
"storage",
"contextMenus",
"tts"
],
"host_permissions": [
"<all_urls>"
],
"background": {
"service_worker": "auto_select.js"
},
"content_security_policy": {
"extension_pages": "script-src 'self'; object-src 'self'; script-src-elem 'self'"
}
}
CodePudding user response:
You need to use chrome.windows.onCreated.
chrome.runtime.onStartup
Fired when a profile that has this extension installed first starts up.
chrome.windows.onCreated
Fired when a window is created.
manifest.json
{
"name": "hoge",
"version": "1.0",
"manifest_version": 3,
"permissions": ["storage"],
"background": {
"service_worker": "background.js"
}
}
CodePudding user response:
I'm assuming that you want to detect the start of a new session, and you want to detect it in the service worker.
That's why you should use the aptly named chrome.storage.session
The following extension get and sets a dummy key in chrome.storage.session
to detect the start of a new session.
How to verify that the extension works correctly:
- Load the extension
- Inspect the service worker.
- The console should show the text "session has started".
- Close the DevTools window, so the service worker won't stay active.
- Wait for the service worker to become inactive.
- Inspect the service worker again.
- The console should now show the text "session is already running".
- If you close Chrome and open it again, the service worker console should again show the text "session has started".
manifest.json
{
"manifest_version": 3,
"name": "Detect Session Start",
"version": "1.0.0",
"permissions": [
"storage"
],
"background": {
"service_worker": "background.js"
}
}
background.js
(async () => {
let { started } = await chrome.storage.session.get("started");
if (started === undefined) {
console.log("session has started");
chrome.storage.session.set({ started: true });
}
else {
console.log("session is already running");
}
})();