I have a chrome extension which is currently consists of a background page and a popup page. There are some initialization happens when the popup is opened. I am using DOM event
doc.addEventListener('DOMContentLoaded', function() { ... }
And the behaviour is correct.
The issue is when closing the popup. Since chrome popup does not throw unload
event I am using what was suggested here. Here is my code
popup.js
bgPage = chrome.extension.getBackgroundPage();
bgPageManager = bgPage.manager(); // This is the exposed api from bg page
bgPageManager.init(chrome.runtime.connect({
name: 'P1'
}));
Here connecting to the runtime and sending the port to background page so that it can listen to onDisconnect
event.
Background.js
function init(port) {
port.onDisconnect.addListener(function() {
// Clean up happens here
stateManager.unregister();
});
}
This works as well.
But the issue is, this onDisconnect
getting fired when the popup is getting opened, not when it is getting closed
The documentation for onDisconnect
event is
An object which allows the addition and removal of listeners for a Chrome event.
Which is not every helpful ;)
So is there anything wrong I am doing, or any way when I can detect the popup close?