1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
5 const Cu = Components.utils;
6 const Cc = Components.classes;
7 const Ci = Components.interfaces;
9 Cu.import("resource://gre/modules/XPCOMUtils.jsm");
11 const MAX_CACHE_SIZE = 250;
12 const PREF_UPDATE = "general.useragent.updates.";
13 const PREF_OVERRIDE = "general.useragent.override.";
14 const XPCOM_SHUTDOWN = "xpcom-shutdown";
15 const HTTP_PROTO_HANDLER = Cc["@mozilla.org/network/protocol;1?name=http"]
16 .getService(Ci.nsIHttpProtocolHandler);
18 XPCOMUtils.defineLazyServiceGetter(this, "cpmm",
19 "@mozilla.org/childprocessmessagemanager;1",
20 "nsISyncMessageSender");
22 function SiteSpecificUserAgent() {
23 this.inParent = Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULRuntime)
24 .processType == Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT;
27 Cu.import("resource://gre/modules/UserAgentOverrides.jsm");
29 Cu.import("resource://gre/modules/Services.jsm");
30 Services.prefs.addObserver(PREF_OVERRIDE, this, false);
31 Services.prefs.addObserver(PREF_UPDATE, this, false);
32 Services.obs.addObserver(this, XPCOM_SHUTDOWN, false);
33 this.userAgentCache = new Map;
37 SiteSpecificUserAgent.prototype = {
38 getUserAgentForURIAndWindow: function ssua_getUserAgentForURIAndWindow(aURI, aWindow) {
40 return UserAgentOverrides.getOverrideForURI(aURI) || HTTP_PROTO_HANDLER.userAgent;
43 let host = aURI.asciiHost;
44 let cachedResult = this.userAgentCache.get(host);
49 let data = { uri: aURI };
50 let result = cpmm.sendRpcMessage("Useragent:GetOverride", data)[0] || HTTP_PROTO_HANDLER.userAgent;
52 if (this.userAgentCache.size >= MAX_CACHE_SIZE) {
53 this.userAgentCache.clear();
56 this.userAgentCache.set(host, result);
60 invalidateCache: function() {
61 this.userAgentCache.clear();
65 this.userAgentCache.clear();
67 Services.obs.removeObserver(this, XPCOM_SHUTDOWN);
68 Services.prefs.removeObserver(PREF_OVERRIDE, this);
69 Services.prefs.removeObserver(PREF_UPDATE, this);
73 observe: function(subject, topic, data) {
75 case "nsPref:changed":
76 this.invalidateCache();
84 classID: Components.ID("{506c680f-3d1c-4954-b351-2c80afbc37d3}"),
85 QueryInterface: XPCOMUtils.generateQI([Ci.nsISiteSpecificUserAgent])
88 this.NSGetFactory = XPCOMUtils.generateNSGetFactory([SiteSpecificUserAgent]);