forked from greasemonkey/greasemonkey
/
greasemonkey.js
483 lines (415 loc) · 15.7 KB
/
greasemonkey.js
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
///////////////////////// Component-global "Constants" /////////////////////////
var DESCRIPTION = "GM_GreasemonkeyService";
var CONTRACTID = "@greasemonkey.mozdev.org/greasemonkey-service;1";
var CLASSID = Components.ID("{77bf3650-1cd6-11da-8cd6-0800200c9a66}");
var Cc = Components.classes;
var Ci = Components.interfaces;
var Cu = Components.utils;
Cu.import("resource://greasemonkey/third-party/getChromeWinForContentWin.js");
Cu.import('resource://greasemonkey/constants.js');
Cu.import("resource://greasemonkey/parseScript.js");
Cu.import("resource://greasemonkey/prefmanager.js");
Cu.import("resource://greasemonkey/util.js");
Cu.import("resource://greasemonkey/xmlhttprequester.js");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
// Only a particular set of strings are allowed. See: http://goo.gl/ex2LJ
var gMaxJSVersion = "ECMAv5";
var gMenuCommands = [];
var gStartupHasRun = false;
var gFileProtocolHandler = Components
.classes["@mozilla.org/network/protocol;1?name=file"]
.getService(Ci.nsIFileProtocolHandler);
var gStringBundle = Components
.classes["@mozilla.org/intl/stringbundle;1"]
.getService(Components.interfaces.nsIStringBundleService)
.createBundle("chrome://greasemonkey/locale/greasemonkey.properties");
var gTmpDir = Components.classes["@mozilla.org/file/directory_service;1"]
.getService(Components.interfaces.nsIProperties)
.get("TmpD", Components.interfaces.nsIFile);
/////////////////////// Component-global Helper Functions //////////////////////
// TODO: Remove this, see #1318.
function alert(msg) {
Cc["@mozilla.org/embedcomp/prompt-service;1"]
.getService(Ci.nsIPromptService)
.alert(null, "Greasemonkey alert", msg);
}
function contentLoad(aEvent) {
var safeWin = aEvent.target.defaultView;
var href = safeWin.location.href;
safeWin.removeEventListener('DOMContentLoaded', contentLoad, true);
safeWin.removeEventListener('load', contentLoad, true);
// Make sure we are still on the page that fired this event, see issue #1083.
// But ignore differences in formats; see issue #1445 and #1631.
var comparisonHref = href.replace(/#.*/, '');
var comparsionUri = aEvent.target.documentURI
.replace(/#.*/, '')
.replace(/\/\/[^\/:]+(:[^\/@]+)?@/, '//');
if (comparisonHref == comparsionUri) {
GM_util.getService().runScripts('document-end', safeWin);
}
}
function createSandbox(
aScript, aContentWin, aChromeWin, aFirebugConsole, aUrl
) {
if (GM_util.inArray(aScript.grants, 'none')) {
// If there is an explicit none grant, use a plain unwrapped sandbox
// with no other content.
var contentSandbox = new Components.utils.Sandbox(
aContentWin,
{
'sandboxName': aScript.id,
'sandboxPrototype': aContentWin,
'wantXrays': false,
});
// GM_info is always provided.
Components.utils.evalInSandbox(
'const GM_info = ' + uneval(aScript.info()), contentSandbox);
// Alias unsafeWindow for compatibility.
Components.utils.evalInSandbox(
'const unsafeWindow = window;', contentSandbox);
if (GM_util.compareFirefoxVersion("16.0") < 0) {
// See #1350. The upstream bug was fixed in Firefox 16; apply workaround
// only in older versions.
contentSandbox.alert = alert;
}
return contentSandbox;
}
var sandbox = new Components.utils.Sandbox(
aContentWin,
{
'sandboxName': aScript.id,
'sandboxPrototype': aContentWin,
'wantXrays': true,
});
sandbox.unsafeWindow = aContentWin.wrappedJSObject;
if (aFirebugConsole) sandbox.console = aFirebugConsole;
if (GM_util.compareFirefoxVersion("16.0") < 0) {
// See #1350. The upstream bug was fixed in Firefox 16; apply workaround
// only in older versions.
sandbox.alert = alert;
}
if (GM_util.inArray(aScript.grants, 'GM_addStyle')) {
sandbox.GM_addStyle = function(css) { GM_addStyle(aContentWin.document, css)};
}
if (GM_util.inArray(aScript.grants, 'GM_log')) {
sandbox.GM_log = GM_util.hitch(new GM_ScriptLogger(aScript), 'log');
}
if (GM_util.inArray(aScript.grants, 'GM_registerMenuCommand')) {
var gmrmc = GM_util.hitch(
null, registerMenuCommand, aContentWin, aChromeWin, aScript);
sandbox.GM_registerMenuCommand = gmrmc;
}
var scriptStorage = new GM_ScriptStorage(aScript);
if (GM_util.inArray(aScript.grants, 'GM_deleteValue')) {
sandbox.GM_deleteValue = GM_util.hitch(scriptStorage, 'deleteValue');
}
if (GM_util.inArray(aScript.grants, 'GM_getValue')) {
sandbox.GM_getValue = GM_util.hitch(scriptStorage, 'getValue');
}
if (GM_util.inArray(aScript.grants, 'GM_setValue')) {
sandbox.GM_setValue = GM_util.hitch(scriptStorage, 'setValue');
}
var scriptResources = new GM_Resources(aScript);
if (GM_util.inArray(aScript.grants, 'GM_getResourceURL')) {
sandbox.GM_getResourceURL = GM_util.hitch(scriptResources, 'getResourceURL', aScript);
}
if (GM_util.inArray(aScript.grants, 'GM_getResourceText')) {
sandbox.GM_getResourceText = GM_util.hitch(scriptResources, 'getResourceText');
}
if (GM_util.inArray(aScript.grants, 'GM_listValues')) {
sandbox.GM_listValues = GM_util.hitch(scriptStorage, 'listValues');
}
if (GM_util.inArray(aScript.grants, 'GM_openInTab')) {
sandbox.GM_openInTab = GM_util.hitch(
null, openInTab, aContentWin, aChromeWin);
}
if (GM_util.inArray(aScript.grants, 'GM_xmlhttpRequest')) {
sandbox.GM_xmlhttpRequest = GM_util.hitch(
new GM_xmlhttpRequester(aContentWin, aChromeWin, aUrl),
'contentStartRequest');
}
Components.utils.evalInSandbox(
'const GM_info = ' + uneval(aScript.info()), sandbox);
return sandbox;
}
function getFirebugConsole(wrappedContentWin, chromeWin) {
try {
return chromeWin.Firebug
&& chromeWin.Firebug.getConsoleByGlobal
&& chromeWin.Firebug.getConsoleByGlobal(wrappedContentWin)
|| null;
} catch (e) {
dump('Greasemonkey: Failure Firebug console:\n' + uneval(e) + '\n');
return null;
}
}
function isTempScript(uri) {
if (uri.scheme != "file") return false;
var file = gFileProtocolHandler.getFileFromURLSpec(uri.spec);
return gTmpDir.contains(file, true);
}
function openInTab(safeContentWin, chromeWin, url, aLoadInBackground) {
if (!GM_util.apiLeakCheck("GM_openInTab")) {
return undefined;
}
if ('undefined' == typeof aLoadInBackground) aLoadInBackground = null;
var browser = chromeWin.gBrowser;
var currentTab = browser.tabs[
browser.getBrowserIndexForDocument(safeContentWin.document)];
var newTab = browser.loadOneTab(url, {'inBackground': aLoadInBackground});
var newWin = GM_windowForTab(newTab, browser);
var afterCurrent = Cc["@mozilla.org/preferences-service;1"]
.getService(Ci.nsIPrefService)
.getBranch("browser.tabs.")
.getBoolPref("insertRelatedAfterCurrent");
if (afterCurrent) {
browser.moveTabTo(newTab, currentTab._tPos + 1);
}
return newWin;
};
function registerMenuCommand(
wrappedContentWin, chromeWin, script,
commandName, commandFunc, accessKey, unused, accessKey2
) {
if (!GM_util.apiLeakCheck("GM_registerMenuCommand")) {
return;
}
if (wrappedContentWin.top != wrappedContentWin) {
// Only register menu commands for the top level window.
return;
}
// Legacy support: if all five parameters were specified, (from when two
// were for accelerators) use the last one as the access key.
if ('undefined' != typeof accessKey2) {
accessKey = accessKey2;
}
if (accessKey
&& (("string" != typeof accessKey) || (accessKey.length != 1))
) {
throw new Error(
gStringBundle.GetStringFromName('error.menu-invalid-accesskey')
.replace('%1', commandName)
);
}
var command = {
name: commandName,
accessKey: accessKey,
commandFunc: commandFunc,
contentWindow: wrappedContentWin,
contentWindowId: GM_util.windowId(wrappedContentWin),
frozen: false};
gMenuCommands.push(command);
};
function runScriptInSandbox(script, sandbox) {
// Eval the code, with anonymous wrappers when/if appropriate.
function evalWithWrapper(code, fileName) {
try {
Components.utils.evalInSandbox(code, sandbox, gMaxJSVersion, fileName, 1);
} catch (e) {
if ("return not in function" == e.message) {
// See #1592; we never anon wrap anymore, unless forced to by a return
// not in a function.
GM_util.logError(
gStringBundle.GetStringFromName('return-not-in-func-deprecated'),
true, // is a warning
fileName,
e.lineNumber
);
Components.utils.evalInSandbox(
GM_util.anonWrap(code), sandbox, gMaxJSVersion, fileName, 1);
} else {
// Otherwise raise.
throw e;
}
}
}
// Eval the code, with a try/catch to report errors cleanly.
function evalWithCatch(code, fileName) {
try {
evalWithWrapper(code, fileName);
} catch (e) {
// Log it properly.
GM_util.logError(e, false, fileName, e.lineNumber);
// Stop the script, in the case of requires, as if it was one big script.
return false;
}
return true;
}
for (var i = 0, require = null; require = script.requires[i]; i++) {
if (!evalWithCatch(require.textContent, require.fileURL)) {
return;
}
}
evalWithCatch(script.textContent, script.fileURL);
}
function startup(aService) {
if (gStartupHasRun) return;
gStartupHasRun = true;
var loader = Cc["@mozilla.org/moz/jssubscript-loader;1"]
.getService(Ci.mozIJSSubScriptLoader);
loader.loadSubScript("chrome://global/content/XPCNativeWrapper.js");
loader.loadSubScript("chrome://greasemonkey/content/config.js");
loader.loadSubScript("chrome://greasemonkey/content/miscapis.js");
loader.loadSubScript("chrome://greasemonkey/content/third-party/mpl-utils.js");
var observerService = Components.classes['@mozilla.org/observer-service;1']
.getService(Components.interfaces.nsIObserverService);
observerService.addObserver(aService, 'document-element-inserted', false);
}
/////////////////////////////////// Service ////////////////////////////////////
function service() {
this.contentLoad = contentLoad;
this.filename = Components.stack.filename;
this.wrappedJSObject = this;
}
////////////////////////////////// Constants ///////////////////////////////////
service.prototype.classDescription = DESCRIPTION;
service.prototype.classID = CLASSID;
service.prototype.contractID = CONTRACTID;
service.prototype._xpcom_categories = [{
category: "app-startup",
entry: DESCRIPTION,
value: CONTRACTID,
service: true
},{
category: "content-policy",
entry: CONTRACTID,
value: CONTRACTID,
service: true
}];
service.prototype.QueryInterface = XPCOMUtils.generateQI([
Ci.nsIObserver,
Ci.nsISupports,
Ci.nsISupportsWeakReference,
Ci.gmIGreasemonkeyService,
Ci.nsIWindowMediatorListener,
Ci.nsIContentPolicy
]);
/////////////////////////////// nsIContentPolicy ///////////////////////////////
service.prototype.shouldLoad = function(ct, cl, org, ctx, mt, ext) {
var ret = Ci.nsIContentPolicy.ACCEPT;
// Don't intercept anything when GM is not enabled.
if (!GM_util.getEnabled()) {
return ret;
}
// Don't interrupt the "view-source:" scheme (which is triggered if the link
// in the error console is clicked), nor the "greasemonkey-script:" scheme.
if ("view-source" == cl.scheme || "greasemonkey-script" == cl.scheme) {
return ret;
}
if ((ct == Ci.nsIContentPolicy.TYPE_DOCUMENT
|| ct == Ci.nsIContentPolicy.TYPE_SUBDOCUMENT)
&& cl.spec.match(/\.user\.js$/)
) {
if (!this._ignoreNextScript && !isTempScript(cl)) {
GM_util.showInstallDialog(cl.spec, ctx, this);
ret = Ci.nsIContentPolicy.REJECT_REQUEST;
}
this._ignoreNextScript = false;
}
return ret;
};
service.prototype.shouldProcess = function(ct, cl, org, ctx, mt, ext) {
return Ci.nsIContentPolicy.ACCEPT;
};
///////////////////////////////// nsIObserver //////////////////////////////////
service.prototype.observe = function(aSubject, aTopic, aData) {
switch (aTopic) {
case 'app-startup':
case 'profile-after-change':
startup(this);
break;
case 'document-element-inserted':
if (!GM_util.getEnabled()) break;
var doc = aSubject;
var win = doc && doc.defaultView;
if (!doc || !doc.location || !win) break;
if (GM_util.isGreasemonkeyable(doc.location.href)) {
this.runScripts('document-start', win);
win.addEventListener('DOMContentLoaded', contentLoad, true);
win.addEventListener('load', contentLoad, true);
}
break;
}
};
//////////////////////////// gmIGreasemonkeyService ////////////////////////////
service.prototype._config = null;
service.prototype.__defineGetter__('config', function() {
if (!this._config) {
// First guarantee instantiation and existence. (So that anything,
// including stuff inside i.e. config._load(), can call
// i.e. config._changed().)
this._config = new Config();
// Then initialize.
this._config.initialize();
}
return this._config;
});
service.prototype.contentDestroyed = function(aContentWindowId) {
this.withAllMenuCommandsForWindowId(null, function(index, command) {
if (GM_util.windowIsClosed(command.contentWindow)
// This content destroyed message matches the command's window id.
|| (aContentWindowId && (command.contentWindowId == aContentWindowId))
) {
// If the window is closed, remove the reference to it.
gMenuCommands.splice(index, 1);
}
}, true); // Don't forget the aForced=true passed here!
};
service.prototype.contentFrozen = function(contentWindowId) {
if (!contentWindowId) return;
this.withAllMenuCommandsForWindowId(contentWindowId,
function(index, command) { command.frozen = true; });
};
service.prototype.contentThawed = function(contentWindowId) {
if (!contentWindowId) return;
this.withAllMenuCommandsForWindowId(contentWindowId,
function(index, command) { command.frozen = false; });
};
service.prototype.runScripts = function(aRunWhen, aWrappedContentWin) {
var url = aWrappedContentWin.document.location.href;
if (!GM_util.getEnabled() || !GM_util.isGreasemonkeyable(url)) return;
if (GM_prefRoot.getValue('enableScriptRefreshing')) {
this._config.updateModifiedScripts(aRunWhen, aWrappedContentWin);
}
var scripts = this.config.getMatchingScripts(function(script) {
try {
return GM_util.scriptMatchesUrlAndRuns(script, url, aRunWhen);
} catch (e) {
GM_util.logError(e, false, e.fileName, e.lineNumber);
// See #1692; Prevent failures like that from being so severe.
return false;
}
});
if (scripts.length > 0) {
this.injectScripts(scripts, url, aWrappedContentWin);
}
};
service.prototype.ignoreNextScript = function() {
this._ignoreNextScript = true;
};
service.prototype.injectScripts = function(
scripts, url, wrappedContentWin
) {
var chromeWin = getChromeWinForContentWin(wrappedContentWin);
var firebugConsole = getFirebugConsole(wrappedContentWin, chromeWin);
for (var i = 0, script = null; script = scripts[i]; i++) {
var sandbox = createSandbox(
script, wrappedContentWin, chromeWin, firebugConsole, url);
runScriptInSandbox(script, sandbox);
}
};
service.prototype.withAllMenuCommandsForWindowId = function(
aContentWindowId, aCallback, aForce
) {
if(!aContentWindowId && !aForce) return;
var l = gMenuCommands.length - 1;
for (var i = l, command = null; command = gMenuCommands[i]; i--) {
if (aForce
|| (command.contentWindowId == aContentWindowId)
) {
aCallback(i, command);
}
}
};
//////////////////////////// Component Registration ////////////////////////////
var NSGetFactory = XPCOMUtils.generateNSGetFactory([service]);