Reputation: 4053
Is there a way to run a callback after extension is disabled/enabled from chrome browser.
Upvotes: 10
Views: 10759
Reputation: 13686
It seems that there is indeed a sibling chrome.management
api namespace where onEnabled
is available, and it does fire for me as expected (when disabling and enabling in developer mode, as well as when not in developer mode).
You can do something like this:
chrome.management.onEnabled.addListener(start);
But note that your manifest will require an extra permission for using this API as already mentioned in the original answer. See here for details in the documentation.
Using chrome.management.onEnabled
seems to be a real sanity saver when flipping your extension on and off as a developer, and all else equal sounds like a good idea for when your users do that as well.
So as of now for my development workflow, I currently trigger my extension's initialization logic on three events in my extension's service worker script which my manifest point at, so that reloading the extension as well as disabling and enabling it all trigger the initialization:
chrome.runtime.onInstalled.addListener(start);
chrome.runtime.onStartup.addListener(start);
chrome.management.onEnabled.addListener(start);
Whereby start
is a function containing my initialization logic.
It's a little non-obvious (to me) why handling its own enablement event, which is basically when the extension is launched, would not be available without the extension requiring management permission. Perhaps there is a different event that can be used for that, within the chrome.runtime
api, or a more correct blueprint for this which I haven't quite figured out yet. If you know a better way, glad to learn about it.
Upvotes: 1
Reputation: 18534
Chrome management API()'s
chrome.management.onEnabled.addListener(function(ExtensionInfo info) {})
chrome.management.onDisabled.addListener(function(ExtensionInfo info) {})
notifies changes of enable and disable of extensions.
Ensure you have
"permissions": [
"management"
],
in your manifest.json
chrome.management.onDisabled.addListener(function(ExtensionInfo) {
console.log(JSON.stringify(ExtensionInfo));
});
P.S : An extension on its own can't monitor when it gets disabled. You'd need a second extension to monitor this. From extension's and user's perspectives, disabling extension has exactly the same effect as closing a browser.
For more information refer documentation.
Upvotes: 17