summaryrefslogtreecommitdiff
path: root/tools/quitter/QuitterObserver.js
blob: fe2a810c93da02d64b8378db596821d39fc05493 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
Components.utils.import("resource://gre/modules/Services.jsm");

const Cc = Components.classes;
const Ci = Components.interfaces;

const CHILD_SCRIPT = "chrome://quitter/content/contentscript.js";

/* XPCOM gunk */
function QuitterObserver() {}

QuitterObserver.prototype = {
  classDescription: "Quitter Observer for use in testing.",
  classID:          Components.ID("{c235a986-5ac1-4f28-ad73-825dae9bad90}"),
  contractID:       "@mozilla.org/quitter-observer;1",
  QueryInterface:   XPCOMUtils.generateQI([Components.interfaces.nsIObserver]),
  _xpcom_categories: [{category: "profile-after-change", service: true }],
  isFrameScriptLoaded: false,

  observe: function(aSubject, aTopic, aData)
  {
    if (aTopic == "profile-after-change") {
      this.init();
    } else if (!this.isFrameScriptLoaded &&
               aTopic == "chrome-document-global-created") {

      var messageManager = Cc["@mozilla.org/globalmessagemanager;1"].
                           getService(Ci.nsIMessageBroadcaster);
      // Register for any messages our API needs us to handle
      messageManager.addMessageListener("Quitter.Quit", this);

      messageManager.loadFrameScript(CHILD_SCRIPT, true);
      this.isFrameScriptLoaded = true;
    } else if (aTopic == "xpcom-shutdown") {
      this.uninit();
    }
  },

  init: function()
  {
    var obs = Services.obs;
    obs.addObserver(this, "xpcom-shutdown", false);
    obs.addObserver(this, "chrome-document-global-created", false);
  },

  uninit: function()
  {
    var obs = Services.obs;
    obs.removeObserver(this, "chrome-document-global-created", false);
  },

  /**
   * messageManager callback function
   * This will get requests from our API in the window and process them in chrome for it
   **/
  receiveMessage: function(aMessage) {
    switch(aMessage.name) {
      case "Quitter.Quit":
        let appStartup = Cc["@mozilla.org/toolkit/app-startup;1"].getService(Ci.nsIAppStartup);
        appStartup.quit(Ci.nsIAppStartup.eForceQuit);
        break;
    }
  }
};

const NSGetFactory = XPCOMUtils.generateNSGetFactory([QuitterObserver]);