8

I develop Chrome extension.

I try to add event listener to chrome.runtime.onSuspend, but it is never called.

I use the following code, but localStorage is not modified and there is no log messages in the console also (I use --enable-logging --v=1 to save log messages to the file).

chrome.runtime.onSuspend.addListener(function() {
  localStorage["suspend"] = new Date();
  console.log("On suspend");
});

Test box: WinXP SP3 x86 with Chrome 28.0.1500.72 m

I've created test extension to easily reproduce this issue:

manifest.json

{
  "manifest_version": 2,

  "name": "Chrome onSuspend test",
  "version": "1.0",

  "background": { 
    "scripts": ["background.js"] }
}

background.js

chrome.runtime.onSuspend.addListener(function() {
  localStorage["suspend"] = new Date();
  console.log("On suspend");
});
Rob W
  • 341,306
  • 83
  • 791
  • 678
Anton
  • 317
  • 3
  • 8

1 Answers1

12

The onSuspend event is only triggered when the event page becomes inactive.

Because you didn't declare persistent: false in your manifest file, the background page is a background page, not an event page. Consequently, the page will never become inactive, and the onSuspend event will never be triggered.

If you wish to turn your background page in an event page, use

...
    "background": { 
        "scripts": ["background.js"],
        "persistent": false
    }
}
Rob W
  • 341,306
  • 83
  • 791
  • 678
  • 3
    Shouldn't background page become inactive on browser close / extension remove or extension disable events? – Anton Jul 23 '13 at 11:05
  • 4
    How can I handle these events? – Anton Jul 23 '13 at 11:06
  • @Anton You can't. When the browser closes, all extensions are terminated without any notice. – Rob W Jul 23 '13 at 13:11
  • @RobW, Is there a way to terminate the background page? Is there a `quit()` function? – Pacerier Sep 10 '17 at 16:48
  • @Pacerier `window.close();` – Rob W Sep 10 '17 at 16:49
  • @RobW, As for event pages, how do we run code when `onSuspend` has resumed? – Pacerier Sep 10 '17 at 18:18
  • Hmm, it seems to re-run the entire script thus disnecessitating `onResume` existence, then in that case, exactly what can be achieved by bg scripts that cannot be done with event scripts? Is there even a single use case for a persistent bg script? – Pacerier Sep 10 '17 at 18:33
  • @Pacerier Background pages existed before event pages were invented. [The `webRequest` API cannot be used in event pages](https://bugs.chromium.org/p/chromium/issues/detail?id=447270), but other than that event pages are generally recommended. – Rob W Sep 10 '17 at 19:15
  • @RobW, Cool, so *moving **forward*** we can say that when webRequest is avail for eventpages, bg pages will have zero usecases and will then be deprecated? – Pacerier Sep 11 '17 at 16:09