Reputation: 607
Is it possible to run some code before chrome packaged app is closing?
Those methods have not helped:
chrome.app.window.current().onClosed
chrome.runtime.onSuspend
window unload event
For example:
chrome.runtime.onSuspend.addListener(function() {
$.ajax({ url: 'http://isup.me/' });
});
After closing application, I do not see any http requests in web monitoring tool (Fiddler2).
Upvotes: 0
Views: 837
Reputation: 11
I can vouch for the workaround (callback in window.create() that registers a .onClosed listener)... it worked perfectly for me, but all the other documented solutions never worked at all in my tests.
Upvotes: 0
Reputation: 77492
When a packaged app is closing, its Event page (defined in the background scripts section of the manifest) receives a chrome.runtime.onSuspend
event. So, your code should be there. But..
This event means it is being unloaded, and only has very little time for cleanup. Quoting:
Once this event is fired, the app runtime starts the process of closing the app: all events stop firing and JavaScript execution is halted. Any asynchronous operations started while handling this event are not guaranteed to complete. Keep the clean-up tasks synchronous and simple.
$.ajax()
is an asynchronous, and rather slow, operation. Therefore, it has a high probability of failing in a clean-up handler.
In principle, this can be made synchronous, but this is disabled in Chrome Apps. So no, you cannot reliably send a network request when your app is closing.
It is possible that there is a workaround using onClosed
handlers:
chrome.app.window.create('window.html', function(win) {
win.onClosed.addListener(function() {
// ...
});
});
This might work, since any asynchronous tasks started from here technically start before onSuspend
is fired, so an event page should not start unloading. But I haven't tried personally.
Upvotes: 2