forked from feiruo/userChromeJS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
UserScriptLoaderPlus.uc.js
1812 lines (1631 loc) · 63.8 KB
/
UserScriptLoaderPlus.uc.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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ==UserScript==
// @name UserScriptLoader 特殊用途版
// @description Greasemonkey 模拟器。新增 GM_saveFile、GM_download 等 API,个人用于特殊用途
// @namespace http://d.hatena.ne.jp/Griever/
// @include main
// @compatibility Firefox 35
// @license MIT License
// @versin 2015.04.12 support @grant none
// @version 0.1.8.4
// @note 0.1.8.4 add persistFlags for PERSIST_FLAGS_AUTODETECT_APPLY_CONVERSION to fix @require save data
// @note 0.1.8.4 Firefox 35 用の修正
// @note 0.1.8.4 エディタで Scratchpad を使えるようにした
// @note 0.1.8.4 GM_notification を独自実装
// @note 0.1.8.3 Firefox 32 で GM_xmlhttpRequest が動かないのを修正
// @note 0.1.8.3 内臓の console を利用するようにした
// @note 0.1.8.3 obsever を使わないようにした
// @note 0.1.8.2 Firefox 22 用の修正
// @note 0.1.8.2 require が機能していないのを修正
// @note 0.1.8.1 Save Script が機能していないのを修正
// @note 0.1.8.0 Remove E4X
// @note 0.1.8.0 @match, @unmatch に超テキトーに対応
// @note 0.1.8.0 .tld を Scriptish を参考にテキトーに改善
// @note 0.1.7.9 __exposedProps__ を付けた
// @note 0.1.7.9 uAutoPagerize との連携をやめた
// @note 0.1.7.8 window.open や target="_blank" で実行されないのを修正
// @note 0.1.7.7 @delay 周りのバグを修正
// @note 0.1.7.6 require で外部ファイルの取得がうまくいかない場合があるのを修正
// @note 0.1.7.5 0.1.7.4 にミスがあったので修正
// @note 0.1.7.4 GM_xmlhttpRequest の url が相対パスが使えなかったのを修正
// @note 0.1.7.3 Google Reader NG Filterがとりあえず動くように修正
// @note 0.1.7.2 document-startが機能していなかったのを修正
// @note 0.1.7.1 .tld がうまく動作していなかったのを修正
// @note 書きなおした
// @note スクリプトを編集時に日本語のファイル名のファイルを開けなかったのを修正
// @note 複数のウインドウを開くとバグることがあったのを修正
// @note .user.js 間で window を共有できるように修正
// @note .tld を簡略化した
// @note スクリプトをキャッシュしないオプションを追加
// @note GM_safeHTMLParser, GM_generateUUID に対応
// @note GM_unregisterMenuCommand, GM_enableMenuCommand, GM_disableMenuCommand に対応
// @note GM_getMetadata に対応(返り値は Array or undefined)
// @note GM_openInTab に第2引数を追加
// @note @require, @resource のファイルをフォルダに保存するようにした
// @note @delay に対応
// @note @bookmarklet に対応(from NinjaKit)
// @note GLOBAL_EXCLUDES を用意した
// @note セキュリティを軽視してみた
// ==/UserScript==
(function(css) {
const GLOBAL_EXCLUDES = [
"chrome:*", "jar:*", "resource:*"
];
const {
classes: Cc,
interfaces: Ci,
utils: Cu,
results: Cr
} = Components;
if (!window.Services) Cu.import("resource://gre/modules/Services.jsm");
if (!window.Downloads) Cu.import("resource://gre/modules/Downloads.jsm");
if (!window.OS) Cu.import("resource://gre/modules/osfile.jsm");
if (window.USL) {
window.USL.destroy();
delete window.USL;
}
var USL = {};
//所有脚本设置保存于JSON
USL.IsSaveSetting = 1;
//保存间隔时间,1000为1秒
USL.saveSettingTimer = 60 * 1000;
// Class
USL.PrefManager = function(str) {
var root = 'UserScriptLoader.';
if (str)
root += str;
this.pref = Services.prefs.getBranch(root);
};
USL.PrefManager.prototype = {
setValue: function(name, value) {
try {
switch (typeof value) {
case 'string':
var str = Cc["@mozilla.org/supports-string;1"].createInstance(Ci.nsISupportsString);
str.data = value;
this.pref.setComplexValue(name, Ci.nsISupportsString, str);
break;
case 'number':
this.pref.setIntPref(name, value);
break;
case 'boolean':
this.pref.setBoolPref(name, value);
break;
}
} catch (e) {}
},
getValue: function(name, defaultValue) {
var value = defaultValue;
try {
switch (this.pref.getPrefType(name)) {
case Ci.nsIPrefBranch.PREF_STRING:
value = this.pref.getComplexValue(name, Ci.nsISupportsString).data;
break;
case Ci.nsIPrefBranch.PREF_INT:
value = this.pref.getIntPref(name);
break;
case Ci.nsIPrefBranch.PREF_BOOL:
value = this.pref.getBoolPref(name);
break;
}
} catch (e) {}
return value;
},
deleteValue: function(name) {
try {
this.pref.deleteBranch(name);
} catch (e) {}
},
listValues: function() this.pref.getChildList("", {}),
};
USL.ScriptEntry = function(aFile) {
this.init.apply(this, arguments);
};
USL.ScriptEntry.prototype = {
includeRegExp: /^https?:\/\/.*/,
excludeRegExp: /^$/,
init: function(aFile) {
this.file = aFile;
this.leafName = aFile.leafName;
this.path = aFile.path;
this.lastModifiedTime = aFile.lastModifiedTime;
this.code = USL.loadText(aFile);
this.getMetadata();
this.disabled = false;
this.requireSrc = "";
this.resources = {};
this.version = "version" in this.metadata ? this.metadata["version"][0] : "未定义";
this.downloadURL = "downloadurl" in this.metadata ? this.metadata["downloadurl"][0] : null;
this.updateURL = "updateurl" in this.metadata ? this.metadata["updateurl"][0] : null;
this.homepageURL = "homepageurl" in this.metadata ? this.metadata["homepageurl"][0] : null;
let dbInfo = USL.database.info[this.leafName];
if (dbInfo) {
this.installTime = dbInfo.installTime;
this.installURL = dbInfo.installURL;
}
if (!this.downloadURL) {
this.downloadURL = this.installURL;
}
this.run_at = "run-at" in this.metadata ? this.metadata["run-at"][0] : "document-end";
this.name = "name" in this.metadata ? this.metadata.name[0] : this.leafName;
if (this.metadata.delay) {
let delay = parseInt(this.metadata.delay[0], 10);
this.delay = isNaN(delay) ? 0 : Math.max(delay, 0);
} else if (this.run_at === "document-idle") {
this.delay = 0;
}
// support @grant none
if ('grant' in this.metadata) {
if (this.metadata['grant'][0] == 'none')
this.grantNone = true;
}
if (this.metadata.match) {
this.includeRegExp = this.createRegExp(this.metadata.match, true);
this.includeTLD = this.isTLD(this.metadata.match);
} else if (this.metadata.include) {
this.includeRegExp = this.createRegExp(this.metadata.include);
this.includeTLD = this.isTLD(this.metadata.include);
}
if (this.metadata.unmatch) {
this.excludeRegExp = this.createRegExp(this.metadata.unmatch, true);
this.excludeTLD = this.isTLD(this.metadata.unmatch);
} else if (this.metadata.exclude) {
this.excludeRegExp = this.createRegExp(this.metadata.exclude);
this.excludeTLD = this.isTLD(this.metadata.exclude);
}
this.prefName = 'scriptival.' + (this.metadata.namespace || 'nonamespace/') + '/' + this.name + '.';
this.__defineGetter__('pref', function() {
delete this.pref;
return this.pref = new USL.PrefManager(this.prefName);
});
if (this.metadata.resource) {
this.metadata.resource.forEach(function(r) {
let res = r.split(/\s+/);
this.resources[res[0]] = {
url: res[1]
};
}, this);
}
this.getRequire();
this.getResource();
},
getMetadata: function() {
this.metadata = {};
let m = this.code.match(/\/\/\s*==UserScript==[\s\S]+?\/\/\s*==\/UserScript==/);
if (!m)
return;
m = (m + '').split(/[\r\n]+/);
for (let i = 0; i < m.length; i++) {
if (!/\/\/\s*?@(\S+)($|\s+([^\r\n]+))/.test(m[i]))
continue;
let name = RegExp.$1.toLowerCase().trim();
let value = RegExp.$3;
if (this.metadata[name]) {
this.metadata[name].push(value);
} else {
this.metadata[name] = [value];
}
}
},
createRegExp: function(urlarray, isMatch) {
let regstr = urlarray.map(function(url) {
if (!isMatch && '/' == url.substr(0, 1) && '/' == url.substr(-1, 1)) {
return url.substring(1, url.length - 1);
}
url = url.replace(/([()[\]{}|+.,^$?\\])/g, "\\$1");
if (isMatch) {
url = url.replace(/\*+|:\/\/\*\\\./g, function(str, index, full) {
if (str === "\\^") return "(?:^|$|\\b)";
if (str === "://*\\.") return "://(?:[^/]+\\.)?";
if (str[0] === "*" && index === 0) return "(?:https?|ftp|file)";
if (str[0] === "*") return ".*";
return str;
});
} else {
url = url.replace(/\*+/g, ".*");
url = url.replace(/^\.\*\:?\/\//, "https?://");
url = url.replace(/^\.\*/, "https?:.*");
}
//url = url.replace(/^([^:]*?:\/\/[^\/\*]+)\.tld\b/,"$1\.(?:com|net|org|info|(?:(?:co|ne|or)\\.)?jp)");
//url = url.replace(/\.tld\//,"\.(?:com|net|org|info|(?:(?:co|ne|or)\\.)?jp)/");
return "^" + url + "$";
}).join('|');
return new RegExp(regstr);
},
isTLD: function(urlarray) {
return urlarray.some(function(url) / ^ . + ? : \/{2,3}?[^\/]+\.tld\b/.test(url));
},
makeTLDURL: function(aURL) {
try {
var uri = Services.io.newURI(aURL, null, null);
uri.host = uri.host.slice(0, -Services.eTLD.getPublicSuffix(uri).length) + "tld";
return uri.spec;
} catch (e) {}
return "";
},
isURLMatching: function(url) {
if (this.disabled) return false;
if (this.excludeRegExp.test(url)) return false;
var tldurl = this.excludeTLD || this.includeTLD ? this.makeTLDURL(url) : "";
if (this.excludeTLD && tldurl && this.excludeRegExp.test(tldurl)) return false;
if (this.includeRegExp.test(url)) return true;
if (this.includeTLD && tldurl && this.includeRegExp.test(tldurl)) return true;
return false;
},
getResource: function() {
if (!this.metadata.resource) return;
var self = this;
for (let [name, aaa] in Iterator(this.resources)) {
let obj = aaa;
let url = obj.url;
let aFile = USL.REQUIRES_FOLDER.clone();
aFile.QueryInterface(Ci.nsILocalFile);
aFile.appendRelativePath(encodeURIComponent(url));
if (aFile.exists() && aFile.isFile()) {
let fileURL = Services.io.getProtocolHandler("file").QueryInterface(Ci.nsIFileProtocolHandler).getURLSpecFromFile(aFile);
USL.getLocalFileContents(fileURL, function(bytes, contentType) {
let ascii = /^text|javascript/.test(contentType);
if (ascii) {
try {
bytes = decodeURIComponent(escape(bytes));
} catch (e) {}
}
obj.bytes = bytes;
obj.contentType = contentType;
});
continue;
}
USL.getContents(url, function(bytes, contentType) {
let ascii = /^text|javascript/.test(contentType);
if (ascii) {
try {
bytes = decodeURIComponent(escape(bytes));
} catch (e) {}
}
let data = ascii ? USL.saveText(aFile, bytes) : USL.saveFile(aFile, bytes);
obj.bytes = data;
obj.contentType = contentType;
});
}
},
getRequire: function() {
if (!this.metadata.require) return;
var self = this;
this.metadata.require.forEach(function(url) {
let aFile = USL.REQUIRES_FOLDER.clone();
aFile.QueryInterface(Ci.nsILocalFile);
aFile.appendRelativePath(encodeURIComponent(url));
if (aFile.exists() && aFile.isFile()) {
self.requireSrc += USL.loadText(aFile) + ";\r\n";
return;
}
USL.getContents(url, function(bytes, contentType) {
let ascii = /^text|javascript/.test(contentType);
if (ascii) {
try {
bytes = decodeURIComponent(escape(bytes));
} catch (e) {}
}
let data = ascii ? USL.saveText(aFile, bytes) : USL.saveFile(aFile, bytes);
self.requireSrc += data + ';\r\n';
});
}, this);
},
};
USL.API = function(script, sandbox, win, doc) {
var self = this;
this.GM_log = function() {
var arr = Array.slice(arguments);
arr.unshift('[' + script.name + ']');
win.console.log.apply(win.console, arr);
// Services.console.logStringMessage("["+ script.name +"] " + Array.slice(arguments).join(", "));
};
this.GM_xmlhttpRequest = function(obj) {
if (typeof(obj) != 'object' || (typeof(obj.url) != 'string' && !(obj.url instanceof String))) return;
var baseURI = Services.io.newURI(win.location.href, null, null);
obj.url = Services.io.newURI(obj.url, null, baseURI).spec;
var req = new XMLHttpRequest();
req.open(obj.method || 'GET', obj.url, true);
if (typeof(obj.headers) == 'object')
for (var i in obj.headers) req.setRequestHeader(i, obj.headers[i]);
['onload', 'onerror', 'onreadystatechange'].forEach(function(k) {
// thx! script uploader
let obj_k = (obj.wrappedJSObject) ? new XPCNativeWrapper(obj.wrappedJSObject[k]) : obj[k];
if (obj_k && (typeof(obj_k) == 'function' || obj_k instanceof Function)) req[k] = function() {
obj_k({
__exposedProps__: {
status: "r",
statusText: "r",
responseHeaders: "r",
responseText: "rw",
readyState: "r",
finalUrl: "r"
},
status: (req.readyState == 4) ? req.status : 0,
statusText: (req.readyState == 4) ? req.statusText : '',
responseHeaders: (req.readyState == 4) ? req.getAllResponseHeaders() : '',
responseText: req.responseText,
readyState: req.readyState,
finalUrl: (req.readyState == 4) ? req.channel.URI.spec : ''
});
};
});
if (obj.overrideMimeType) req.overrideMimeType(obj.overrideMimeType);
var c = 0;
var timer = setInterval(function() {
if (req.readyState == 1 || ++c > 100) {
clearInterval(timer);
req.send(obj.data || null);
}
}, 10);
USL.debug(script.name + ' GM_xmlhttpRequest ' + obj.url);
};
this.GM_addStyle = function GM_addStyle(code) {
var head = doc.getElementsByTagName('head')[0];
if (head) {
var style = doc.createElement('style');
style.type = 'text/css';
style.appendChild(doc.createTextNode(code + ''));
head.appendChild(style);
return style;
}
};
this.GM_setValue = function(name, value) {
if (!USL.IsSaveSetting) {
return USL.USE_STORAGE_NAME.indexOf(name) >= 0 ?
USL.database.pref[script.prefName + name] = value :
script.pref.setValue(name, value);
} else {
USL.database.pref[script.prefName + name] = value;
if (USL.saveSettingTimeout) {
clearTimeout(USL.saveSettingTimeout)
USL.saveSettingTimeout = null;
}
USL.saveSettingTimeout = setTimeout(function() {
USL.saveSetting()
}, USL.saveSettingTimer)
}
};
this.GM_getValue = function(name, def) {
if (!USL.IsSaveSetting) {
return USL.USE_STORAGE_NAME.indexOf(name) >= 0 ?
USL.database.pref[script.prefName + name] || def :
script.pref.getValue(name, def);
} else return USL.database.pref[script.prefName + name] || def;
};
this.GM_listValues = function() {
var p = script.pref.listValues();
var s = [x
for (x in USL.database.pref[script.prefName + name])
];
s.forEach(function(e, i, a) a[i] = e.replace(script.prefName, ''));
p.push.apply(p, s);
return p;
};
this.GM_deleteValue = function(name) {
if (!USL.IsSaveSetting) {
return USL.USE_STORAGE_NAME.indexOf(name) >= 0 ?
delete USL.database.pref[script.prefName + name] :
script.pref.deleteValue(name);
} else return delete USL.database.pref[script.prefName + name]
};
this.GM_registerMenuCommand = function(label, func, aAccelKey, aAccelModifiers, aAccessKey) {
let uuid = self.GM_generateUUID();
win.USL_registerCommands[uuid] = {
label: label,
func: func,
accelKey: aAccelKey,
accelModifiers: aAccelModifiers,
accessKey: aAccessKey,
tooltiptext: script.name
};
return uuid;
};
this.GM_unregisterMenuCommand = function(aUUID) {
return delete win.USL_registerCommands[aUUID];
};
this.GM_enableMenuCommand = function(aUUID) {
let item = win.USL_registerCommands[aUUID];
if (item) delete item.disabled;
};
this.GM_disableMenuCommand = function(aUUID) {
let item = win.USL_registerCommands[aUUID];
if (item) item.disabled = "true";
};
this.GM_getResourceText = function(name) {
let obj = script.resources[name];
if (obj) return obj.bytes;
};
this.GM_getResourceURL = function(name) {
let obj = script.resources[name];
try {
if (obj) return 'data:' + obj.contentType + ';base64,' + btoa(obj.bytes);
} catch (e) {
USL.error(e);
}
};
this.GM_getMetadata = function(key) {
return script.metadata[key] ? script.metadata[key].slice() : void 0;
};
this.GM_notification = function(msg, title, icon, callback) {
if (!icon)
icon = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAALEgAACxIB0t1+/AAAACx0RVh0Q3JlYXRpb24gVGltZQBTdW4gMzAgTWFyIDIwMDggMTc6MjI6NDcgLTA1MDDUnvhKAAAAB3RJTUUH2AQGETEsCzNv6AAAAk9JREFUOE9lU09Ik3EYfo91mtFhY2NtKxexQGOMMJU5sojoYGU3g1UyNUQ0Kvpjukozgmqm1iyyr4zMpBweyvCybh7NOgjq+mYUdeu449P7vl+bW/7g4ff+eZ6Hl9/7feT3+8nn85HH4yG3201Op5PsdnsB8QhVMjpPVlDqwHYyi3t6igt5sMDDSDDM9r2EQ+WEiFcRL+bpcTgcJfgnhKCpoiBEwy7ChWpKHy4nk3ObcDcYsGhBhInGLWgNEaJ7CM1BwvlqC40BNavL8/X0hKmhp45SvYzXXbuR+9wHLN/HwosmnUJuyaUufeEJX3Rq0F2/+c9YR1DJKl4ZBDKPgG9PYM5e1BuZJNeHuN+vPOGLTg2G24KYGTgCo2UHkxJKNiZPwxiPAWuvYLxp4fgMGz3m/gPlCV90lkFHDSYu1WC2LwysjgDmU0Q6IyirLQN+TK/HpqGTCe9tvB6iU4NYeKspBvPJo9bo2eegnQRyE/Dr43q8Nq5TzCePqYHo1IDXEr26fxNyi7cKBsbDs4wu4PccjOQ5GCPtbPBSDXKLAxC+6NSAH8Uma8PyPQx2H8eX9zeA7xM8/jvg5wxjmvNJfP1wE0PXTuhG5CHliy0Y5DeQTfei+WAlooFt6K8KYHRfAHf4jgU8aOV69tN15ZUYSMCFdOpKiN3v6rqQGdXHhPmMMWZtQB6YpxSe8P83kB/GlBUtTZ2y1rk6bInk5m9jaYpXy33hCb9g4HK5FFy0tYXo9uVaWuFYxyyG1KXPsS2vKTEoKnoZVYxIEST3buQS/QUCx7vn2Dh8TQAAAABJRU5ErkJggg==";
let aBrowser = win.QueryInterface(Ci.nsIDOMWindow)
.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIWebNavigation)
.QueryInterface(Ci.nsIDocShell).chromeEventHandler;
let buttons = [{
label: msg,
accessKey: 'U',
callback: function(aNotification, aButton) {
try {
if (callback)
callback.call(win);
} catch (e) {
self.GM_log(new Error(e));
}
}.bind(this)
}];
let notificationBox = gBrowser.getNotificationBox(aBrowser);
let notification = notificationBox.appendNotification(
title, 'USL_notification', icon,
notificationBox.PRIORITY_INFO_MEDIUM,
buttons);
};
};
USL.API.prototype = {
GM_openInTab: function(url, loadInBackground, reuseTab) {
openLinkIn(url, loadInBackground ? "tabshifted" : "tab", {});
},
GM_setClipboard: function(str) {
if (str.constructor === String || str.constructor === Number) {
Cc['@mozilla.org/widget/clipboardhelper;1'].getService(Ci.nsIClipboardHelper).copyString(str);
}
},
GM_safeHTMLParser: function(code) {
let HTMLNS = "http://www.w3.org/1999/xhtml";
let gUnescapeHTML = Cc["@mozilla.org/feed-unescapehtml;1"].getService(Ci.nsIScriptableUnescapeHTML);
let doc = document.implementation.createDocument(HTMLNS, "html", null);
let body = document.createElementNS(HTMLNS, "body");
doc.documentElement.appendChild(body);
body.appendChild(gUnescapeHTML.parseFragment(code, false, null, body));
return doc;
},
GM_generateUUID: function() {
return Cc["@mozilla.org/uuid-generator;1"].getService(Ci.nsIUUIDGenerator).generateUUID().toString();
},
// 以下我新增的
/**
* filename 支持 text/a.html
*/
GM_saveFile: function(data, filename, dir) {
var file = getDownloadFile(filename, dir);
var converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"].createInstance(Ci.nsIScriptableUnicodeConverter);
converter.charset = 'UTF-8';
var istream = converter.convertToInputStream(data);
var ostream = FileUtils.openSafeFileOutputStream(file);
NetUtil.asyncCopy(istream, ostream, function(status) {
if (!Components.isSuccessCode(status)) {
// Handle error!
return;
}
// Data has been written to the file.
});
},
GM_saveFileSync: function(data, filename, dir) {
var file = getDownloadFile(filename, dir);
var converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"].createInstance(Ci.nsIScriptableUnicodeConverter);
converter.charset = 'UTF-8';
data = converter.ConvertFromUnicode(data);
var foStream = Cc['@mozilla.org/network/file-output-stream;1'].createInstance(Ci.nsIFileOutputStream);
foStream.init(file, 0x02 | 0x08 | 0x20, 0664, 0);
foStream.write(data, data.length);
foStream.close();
},
/**
* http://tampermonkey.net/documentation.php?ext=dhdg#GM_download
* GM_download(url, name) GM_download(details)
*/
GM_download: function(url, name, dir) {
var details;
if (arguments.length == 1) {
details = arguments[0];
} else {
details = {
url: arguments[0],
name: arguments[1],
dir: arguments[2],
};
}
if (!details.name) {
try {
details.name = getFileBaseName(url);
} catch (ex) {}
}
details.onload || (details.onload = function() {});
var uri;
try {
uri = NetUtil.newURI(url);
} catch (ex) {
USL.error(ex)
return;
}
var targetFile = getDownloadFile(details.name, details.dir);
var persist = Cc["@mozilla.org/embedding/browser/nsWebBrowserPersist;1"]
.createInstance(Ci.nsIWebBrowserPersist);
persist.persistFlags = persist.PERSIST_FLAGS_FROM_CACHE | persist.PERSIST_FLAGS_REPLACE_EXISTING_FILES;
persist.progressListener = {
onProgressChange: function(progress, request, aCurSelfProgress, aMaxSelfProgress, aCurTotalProgress, aMaxTotalProgress) {},
onStateChange: function(progress, request, flags, status) {
if ((flags & Ci.nsIWebProgressListener.STATE_STOP) && status == 0) {
details.onload(targetFile.path);
}
}
};
persist.saveURI(uri, null, uri, Ci.nsIHttpChannel.REFERRER_POLICY_NO_REFERRER_WHEN_DOWNGRADE, null, null, targetFile, null);
},
GM_run: function(path, args) {
var file = Cc['@mozilla.org/file/local;1'].createInstance(Ci.nsILocalFile);
var process = Cc['@mozilla.org/process/util;1'].createInstance(Ci.nsIProcess);
file.initWithPath(path);
if (!args) args = [];
try {
if (file.isExecutable()) {
process.init(file);
process.runw(false, args, args.length);
} else {
file.launch();
}
} catch (ex) {
USL.log(ex);
}
},
};
function safeFileName(title) {
return title.replace(/:/g, ':').replace(/[\\\|\:\*\"\?\<\>]/g, "_");
}
// https://developer.mozilla.org/en-US/Add-ons/Code_snippets/File_I_O
function getDownloadFile(filename, dir) {
if (!getDownloadFile.isSeted) {
// 注册一个自定义路径供下面调用
Cc["@mozilla.org/file/directory_service;1"]
.getService(Ci.nsIProperties)
.set("Dwnld", USL.DOWNLOAD_FOLDER);
getDownloadFile.isSeted = true;
}
var pathArr = dir ? dir.split(/\/|\\/) : [];
filename = safeFileName(filename)
pathArr.push(filename);
var file = FileUtils.getFile("Dwnld", pathArr, true);
return file;
}
function playSoundFile(aFilePath) {
var ios = Components.classes["@mozilla.org/network/io-service;1"]
.createInstance(Components.interfaces["nsIIOService"]);
try {
var uri = ios.newURI(aFilePath, "UTF-8", null);
} catch (e) {
return;
}
var file = uri.QueryInterface(Components.interfaces.nsIFileURL).file;
if (!file.exists())
return;
play(uri);
}
function play(aUri) {
var sound = Components.classes["@mozilla.org/sound;1"]
.createInstance(Components.interfaces["nsISound"]);
sound.play(aUri);
}
USL.database = {
info: {},
pref: {},
resource: {}
};
USL.readScripts = [];
USL.USE_STORAGE_NAME = ['cache', 'cacheInfo'];
USL.initialized = false;
USL.__defineGetter__("pref", function() {
delete this.pref;
return this.pref = new USL.PrefManager();
});
USL.__defineGetter__("SCRIPTS_FOLDER", function() {
let folderPath = this.pref.getValue('SCRIPTS_FOLDER', "");
let aFolder = Cc['@mozilla.org/file/local;1'].createInstance(Ci.nsILocalFile)
if (!folderPath) {
aFolder.initWithPath(Services.dirsvc.get("UChrm", Ci.nsIFile).path);
aFolder.appendRelativePath('UserScriptLoader');
} else {
aFolder.initWithPath(folderPath);
}
if (!aFolder.exists() || !aFolder.isDirectory()) {
aFolder.create(Ci.nsIFile.DIRECTORY_TYPE, 0664);
}
delete this.SCRIPTS_FOLDER;
return this.SCRIPTS_FOLDER = aFolder;
});
USL.__defineGetter__("REQUIRES_FOLDER", function() {
let aFolder = this.SCRIPTS_FOLDER.clone();
aFolder.QueryInterface(Ci.nsILocalFile);
aFolder.appendRelativePath('require');
if (!aFolder.exists() || !aFolder.isDirectory()) {
aFolder.create(Ci.nsIFile.DIRECTORY_TYPE, 0664);
}
delete this.REQUIRES_FOLDER;
return this.REQUIRES_FOLDER = aFolder;
});
USL.__defineGetter__("TEMP_FOLDER", function() {
let aFolder = this.SCRIPTS_FOLDER.clone();
aFolder.QueryInterface(Ci.nsILocalFile);
aFolder.appendRelativePath('temp');
if (!aFolder.exists() || !aFolder.isDirectory()) {
aFolder.create(Ci.nsIFile.DIRECTORY_TYPE, 0664);
}
delete this.TEMP_FOLDER;
return this.TEMP_FOLDER = aFolder;
});
USL.__defineGetter__("NEW_VERSION_FOLDER", function() {
let aFolder = this.SCRIPTS_FOLDER.clone();
aFolder.QueryInterface(Ci.nsILocalFile);
aFolder.appendRelativePath('newVersion');
if (!aFolder.exists() || !aFolder.isDirectory()) {
aFolder.create(Ci.nsIFile.DIRECTORY_TYPE, 0664);
}
delete this.NEW_VERSION_FOLDER;
return this.NEW_VERSION_FOLDER = aFolder;
});
USL.__defineGetter__("EDITOR", function() {
delete this.EDITOR;
return this.EDITOR = this.pref.getValue('EDITOR', "") || Services.prefs.getCharPref("view_source.editor.path");
});
USL.__defineGetter__("disabled_scripts", function() {
let ds = this.pref.getValue('script.disabled', '');
delete this.disabled_scripts;
return this.disabled_scripts = ds ? ds.split('|') : [];
});
USL.__defineGetter__("GLOBAL_EXCLUDES_REGEXP", function() {
let regexp = null;
let ge = USL.pref.getValue('GLOBAL_EXCLUDES', null);
ge = ge ? ge.trim().split(/\s*\,\s*/) : GLOBAL_EXCLUDES;
try {
regexp = new RegExp(ge.map(USL.wildcardToRegExpStr).join("|"));
} catch (e) {
regexp = /^(?:chrome|resource|jar):/;
}
delete this.GLOBAL_EXCLUDES_REGEXP;
return this.GLOBAL_EXCLUDES_REGEXP = regexp;
});
USL.__defineGetter__("DOWNLOAD_FOLDER", function() {
var prefs = Services.prefs.getBranch("browser.download.");
try {
var aFolder = prefs.getComplexValue("dir", Ci.nsILocalFile);
} catch (ex) {
var aFolder = FileUtils.getFile("DfltDwnld", []);
}
delete this.DOWNLOAD_FOLDER;
return this.DOWNLOAD_FOLDER = aFolder;
});
var DISABLED = true;
USL.__defineGetter__("disabled", function() DISABLED);
USL.__defineSetter__("disabled", function(bool) {
if (bool) {
this.icon.setAttribute("state", "disable");
this.icon.setAttribute("tooltiptext", "UserScriptLoader已禁用");
// gBrowser.mPanelContainer.removeEventListener("DOMWindowCreated", this, false);
} else {
this.icon.setAttribute("state", "enable");
this.icon.setAttribute("tooltiptext", "UserScriptLoader已启用");
// gBrowser.mPanelContainer.addEventListener("DOMWindowCreated", this, false);
}
return DISABLED = bool;
});
var DEBUG = USL.pref.getValue('DEBUG', false);
USL.__defineGetter__("DEBUG", function() DEBUG);
USL.__defineSetter__("DEBUG", function(bool) {
DEBUG = !!bool;
let elem = $("UserScriptLoader-debug-mode");
if (elem) elem.setAttribute("checked", DEBUG);
return bool;
});
var HIDE_EXCLUDE = USL.pref.getValue('HIDE_EXCLUDE', false);
USL.__defineGetter__("HIDE_EXCLUDE", function() HIDE_EXCLUDE);
USL.__defineSetter__("HIDE_EXCLUDE", function(bool) {
HIDE_EXCLUDE = !!bool;
let elem = $("UserScriptLoader-hide-exclude");
if (elem) elem.setAttribute("checked", HIDE_EXCLUDE);
return bool;
});
var ALLOW_NOTIFY = USL.pref.getValue('ALLOW_NOTIFY', true);
USL.__defineGetter__("ALLOW_NOTIFY", function() ALLOW_NOTIFY);
USL.__defineSetter__("ALLOW_NOTIFY", function(bool) {
ALLOW_NOTIFY = !!bool;
let elem = $("UserScriptLoader-allow-notify");
if (elem) elem.setAttribute("checked", ALLOW_NOTIFY);
return bool;
});
var AUTO_RELOAD_PAGE = USL.pref.getValue('AUTO_RELOAD_PAGE', true);
USL.__defineGetter__("AUTO_RELOAD_PAGE", function() AUTO_RELOAD_PAGE);
USL.__defineSetter__("AUTO_RELOAD_PAGE", function(bool) {
AUTO_RELOAD_PAGE = !!bool;
let elem = $("UserScriptLoader-auto-reload-page");
if (elem) elem.setAttribute("checked", AUTO_RELOAD_PAGE);
return bool;
});
var CACHE_SCRIPT = USL.pref.getValue('CACHE_SCRIPT', true);
USL.__defineGetter__("CACHE_SCRIPT", function() CACHE_SCRIPT);
USL.__defineSetter__("CACHE_SCRIPT", function(bool) {
CACHE_SCRIPT = !!bool;
let elem = $("UserScriptLoader-cache-script");
if (elem) elem.setAttribute("checked", CACHE_SCRIPT);
return bool;
});
var MY_EDITOR = USL.pref.getValue('MY_EDITOR', true);
USL.__defineGetter__("MY_EDITOR", function() MY_EDITOR);
USL.__defineSetter__("MY_EDITOR", function(bool) {
MY_EDITOR = !!bool;
let elem = $("UserScriptLoader-use-myeditor");
if (elem) elem.setAttribute("checked", MY_EDITOR);
return bool;
});
USL.getFocusedWindow = function() {
var win = document.commandDispatcher.focusedWindow;
return (!win || win == window) ? content : win;
};
USL.init = function() {
USL.loadSetting();
USL.style = addStyle(css);
USL.icon = $('urlbar-icons').appendChild($C("image", {
id: "UserScriptLoader-icon",
context: "UserScriptLoader-popup",
onclick: "USL.iconClick(event);",
style: "padding: 0px 2px;",
tooltiptext: "油猴脚本管理器(左键开关)"
}));
var xml = '\
<menupopup id="UserScriptLoader-popup" onpopupshowing="USL.onPopupShowing(event);" onpopuphidden="USL.onPopupHidden(event);" onclick="USL.menuClick(event);">\
<menuseparator id="UserScriptLoader-menuseparator"/>\
<menu label="脚本命令" id="UserScriptLoader-register-menu">\
<menupopup id="UserScriptLoader-register-popup"/>\
</menu>\
<menu label="管理菜单" id="UserScriptLoader-submenu">\
<menupopup id="UserScriptLoader-submenu-popup">\
<menuitem label="删除 Pref" id="UserScriptLoader-delete-pref" oncommand="USL.deleteStorage(\'pref\');" tooltiptext="删除存储在 UserScriptLoader.json 文件中的 pref"/>\
<menuitem label="删除额外信息" id="UserScriptLoader-delete-info" oncommand="USL.deleteStorage(\'info\');" tooltiptext="删除存储在 UserScriptLoader.json 文件中的额外信息,包括安装地址、安装时间"/>\
<menuseparator/>\
<menuitem label="隐藏未触发脚本" id="UserScriptLoader-hide-exclude" type="checkbox" checked="' + USL.HIDE_EXCLUDE + '" oncommand="USL.HIDE_EXCLUDE = !USL.HIDE_EXCLUDE;"/>\
<menuitem label="打开脚本文件夹" id="UserScriptLoader-openFolderMenu" oncommand="USL.openFolder();"/>\
<menuitem label="重新载入脚本" oncommand="USL.rebuild();"/>\
<menuitem label="缓存所有脚本" id="UserScriptLoader-cache-script" type="checkbox" checked="' + USL.CACHE_SCRIPT + '" tooltiptext="缓存脚本则不检查文件的修改时间,修改文件后并不会自动载入" oncommand="USL.CACHE_SCRIPT = !USL.CACHE_SCRIPT;"/>\
<menuitem label="Use My Editor" id="UserScriptLoader-use-myeditor" type="checkbox" checked="' + USL.MY_EDITOR + '" oncommand="USL.MY_EDITOR = !USL.MY_EDITOR;"/>\
<menuitem label="启用调试模式" id="UserScriptLoader-debug-mode" type="checkbox" checked="' + USL.DEBUG + '" oncommand="USL.DEBUG = !USL.DEBUG;"/>\
<menuitem label="自动刷新页面" id="UserScriptLoader-auto-reload-page" type="checkbox" checked="' + USL.AUTO_RELOAD_PAGE + '" oncommand="USL.AUTO_RELOAD_PAGE = !USL.AUTO_RELOAD_PAGE;" />\
</menupopup>\
</menu>\
<menu label="相关网站">\
<menupopup>\
<menuitem label="greasyfork.org" oncommand="USL.openTab(\'https://greasyfork.org/scripts\');" />\
<menuitem label="Userscripts.org" oncommand="USL.openTab(\'http://userscripts.org:8080/\');" />\
<menuseparator/>\
<menuitem label="Greasespot 博客" oncommand="USL.openTab(\'http://www.greasespot.net/\');" />\
<menuitem label="Greasespot Wiki" oncommand="USL.openTab(\'http://wiki.greasespot.net/\');" />\
<menuitem label="Greasemonkey 手册" oncommand="USL.openTab(\'http://wiki.greasespot.net/Greasemonkey_Manual\');" />\
<menuseparator/>\
<menuitem label="GM 脚本开发小册子" oncommand="USL.openTab(\'http://jixunmoe.github.io/gmDevBook\');"/>\
</menupopup>\
</menu>\
<menuseparator/>\
<menuitem label="检查脚本更新" id="UserScriptLoader-check-script" oncommand="USL.checkScripts();" />\
<menuitem label="为本站搜索脚本" id="UserScriptLoader-find-script" oncommand="USL.findscripts();" onclick="if(event.button !=2) USL.findscripts(\'search\');" />\
<menuitem label="保存当前页面脚本" id="UserScriptLoader-saveMenu" oncommand="USL.saveScript();"/>\
</menupopup>\
';
var range = document.createRange();
range.selectNodeContents($('mainPopupSet'));
range.collapse(false);
range.insertNode(range.createContextualFragment(xml.replace(/\n|\t/g, '')));
range.detach();
USL.popup = $('UserScriptLoader-popup');
USL.menuseparator = $('UserScriptLoader-menuseparator');
USL.registMenu = $('UserScriptLoader-register-menu');
USL.saveMenu = $('UserScriptLoader-saveMenu');
USL.rebuild();
USL.disabled = USL.pref.getValue('disabled', false);
Array.from(gBrowser.browsers, browser => {
browser.addEventListener('DOMWindowCreated', USL, false);
});
gBrowser.mTabContainer.addEventListener('TabOpen', USL, false);
gBrowser.mTabContainer.addEventListener('TabClose', USL, false);
window.addEventListener('unload', USL, false);
USL.initialized = true;
};
USL.uninit = function() {
Array.from(gBrowser.browsers, browser => {
browser.removeEventListener('DOMWindowCreated', USL, false);
});
gBrowser.mTabContainer.removeEventListener('TabOpen', USL, false);
gBrowser.mTabContainer.removeEventListener('TabClose', USL, false);
window.removeEventListener('unload', USL, false);
};
USL.destroy = function() {
USL.saveSetting();
USL.uninit();
var e = document.getElementById("UserScriptLoader-icon");
if (e) e.parentNode.removeChild(e);
var e = document.getElementById("UserScriptLoader-popup");
if (e) e.parentNode.removeChild(e);
if (USL.style) USL.style.parentNode.removeChild(USL.style);
USL.disabled = true;
};
USL.handleEvent = function(event) {
switch (event.type) {
case "DOMWindowCreated":
var win = event.target.defaultView;
win.USL_registerCommands = {};
win.USL_run = [];
win.USL_match = [];
if (USL.disabled) return;
if (USL.readScripts.length === 0) return;
USL.injectScripts(win);
break;
case 'TabOpen':
event.target.linkedBrowser.addEventListener('DOMWindowCreated', USL, false);
break;
case 'TabClose':
event.target.linkedBrowser.removeEventListener('DOMWindowCreated', USL, false);
break;
case "unload":
USL.saveSetting();
USL.uninit();
break;
}
};
USL.createMenuitem = function() {
if (USL.popup.firstChild != USL.menuseparator) {
var range = document.createRange();
range.setStartBefore(USL.popup.firstChild);
range.setEndBefore(USL.menuseparator);
range.deleteContents();
range.detach();
}
USL.readScripts.forEach(function(script) {
let m = document.createElement('menuitem');
m.setAttribute('label', script.name + '(' + script.version + ')');
m.setAttribute('tooltiptext', '左键启用/禁用,中键打开主页,右键编辑');
m.setAttribute("class", "UserScriptLoader-item");
m.setAttribute('checked', !script.disabled);
m.setAttribute('type', 'checkbox');
m.setAttribute('oncommand', 'this.script.disabled = !this.script.disabled;if(USL.AUTO_RELOAD_PAGE)BrowserReload();');
m.script = script;
USL.popup.insertBefore(m, USL.menuseparator);
});
};
USL.rebuild = function() {
USL.disabled_scripts = [x.leafName
for each(x in USL.readScripts) if (x.disabled)
];
USL.pref.setValue('script.disabled', USL.disabled_scripts.join('|'));
let newScripts = [];
let ext = /\.user\.js$/i;
let files = USL.SCRIPTS_FOLDER.directoryEntries.QueryInterface(Ci.nsISimpleEnumerator);
while (files.hasMoreElements()) {
let file = files.getNext().QueryInterface(Ci.nsIFile);
if (!ext.test(file.leafName)) continue;