forked from ywzhaiqi/userChromeJS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuAutoPagerize2.uc.js
2994 lines (2690 loc) · 109 KB
/
uAutoPagerize2.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 uAutoPagerize2
// @namespace http://d.hatena.ne.jp/Griever/
// @description 自动翻页,中文规则增强改进版
// @include main
// @modified ywzhaiqi
// @compatibility Firefox 17
// @charset UTF-8
// @version 2014.10.13
// version 0.3.0
// @inspect window.uAutoPagerize
// @startup window.uAutoPagerize.init();
// @shutdown window.uAutoPagerize.destroy();
// @config window.uAutoPagerize.edit(uAutoPagerize.file_CN, null, true);uAutoPagerize.edit(uAutoPagerize.file);
// @homepageURL https://github.com/ywzhaiqi/userChromeJS/tree/master/uAutoPagerize2
// @downloadURL https://github.com/ywzhaiqi/userChromeJS/raw/master/uAutoPagerize2/uAutoPagerize2.uc.js
// @reviewURL http://bbs.kafan.cn/thread-1555846-1-1.html
// @optionsURL about:config?filter=uAutoPagerize.
// @note 0.3.0 本家に倣って Cookie の処理を変更した
// @note 0.2.9 remove E4X
// @note 0.2.8 履歴に入れる機能を廃止
// @note 0.2.7 Firefox 14 でとりあえず動くように修正
// @note 0.2.6 組み込みの SITEINFO を修正
// @note 0.2.5 MICROFORMAT も設定ファイルから追加・無効化できるようにした
// @note 0.2.5 スペースアルクで動かなくなってたのを修正
// @note 0.2.4 SITEINFO のソートをやめてチェックの仕方を変えた(一度SITEINFOを更新した方がいいかも)
// @note 0.2.4 naver まとめ、kakaku.com 修正
// @note 0.2.3 kakaku.com のスペック検索に対応
// @note 0.2.3 Fx7 くらいから xml で動かなくなってたのを修正
// @note 0.2.3 ver 0.2.2 で nextLink に form 要素が指定されている場合などに動かなくなってたのを修正
// @note 0.2.2 コンテキストメニューが意外と邪魔だったので葬った
// @note 0.2.1 コンテキストメニューに次のページを開くメニューを追加
// @note 0.2.1 区切りのアイコンをクリックしても色が変わらなかったのを修正
// @note 0.2.0 INCLUDE を設定できるようにした
// @note 0.2.0 INCLUDE, EXCLUDE をワイルドカード式にした
// @note 0.2.0 アイコンに右クリックメニューを付けた
// @note 0.2.0 スクロールするまでは次を読み込まないオプションをつけた
// ==/UserScript==
// this script based on
// AutoPagerize version: 0.0.41 2009-09-05T16:02:17+09:00 (http://autopagerize.net/)
// oAutoPagerize (http://d.hatena.ne.jp/os0x/searchdiary?word=%2a%5boAutoPagerize%5d)
//
// Released under the GPL license
// http://www.gnu.org/copyleft/gpl.html
(function(css) {
var Config = {
isUrlbar: 1, // 放置的位置,0 为可移动按钮,1 为地址栏
ORIGINAL_SITEINFO: false, // 原版JSON规则是否启用?以国外网站为主
UPDATE_CN_SITEINFO_DAYS: 7, // 更新中文规则的间隔(天)
SEND_COOKIE: false, // 是否额外的获取 cookie?百度有问题时需要清除 cookie
// 默认值,有些可在右键菜单直接修改
MAX_PAGER_NUM: -1, // 默认最大翻页数, -1表示无限制
IMMEDIATELY_PAGER_NUM: 3, // 立即加载的默认页数
USE_IFRAME: true, // 是否启用 iframe 加载下一页(浏览器级,默认只允许 JavaScript 和 image,在 createIframe 中可设置其它允许)
PRELOADER_NEXTPAGE: false, // 提前预读下一页..就是翻完第1页,立马预读第2页,翻完第2页,立马预读第3页..(大幅加快翻页快感-_-!!)
ADD_TO_HISTORY: false, // 添加下一页链接到历史记录
SEPARATOR_RELATIVELY: true, // 分隔符.在使用上滚一页或下滚一页的时候是否保持相对位置..
};
// 自定义数据库、中文数据库、默认的 JSON 数据库摆放的文件夹,例如 Local
// 不要在这里更改,请到右键设置中更改(需重启生效)
// 或 about:config 中更改 uAutoPagerize.DB_FOLDER 的值(如果没有手动新建一个)
var DB_FOLDER = "";
// 额外的设置,具体在配置文件中
var prefs = {
pauseA: false, // 快速停止翻页开关
ipages: [false, 2],
lazyImgSrc: 'zoomfile|file|original|load-src|_src|imgsrc|real_src|src2|data-lazyload-src|data-ks-lazyload|data-lazyload|data-src|data-original|data-thumb|data-imageurl|data-defer-src|data-placeholder',
};
// ワイルドカード(*)で記述する
var INCLUDE = [
"*"
];
var EXCLUDE = [
'https://mail.google.com/*',
'https://maps.google.*/*',
'https://www.google.com/maps/*',
'https://www.google.com/calendar*',
'http://www.google.*/reader/*',
'*://app.yinxiang.com/*',
'*://www.dropbox.com/*',
'*://www.toodledo.com/*',
'*://www.wumii.com/*',
'http://www.cnbeta.com/*'
];
var MY_SITEINFO = [
{
url : '^https?://mobile\\.twitter\\.com/'
,nextLink : '//div[contains(concat(" ",normalize-space(@class)," "), " w-button-more ")]/a[@href]'
,pageElement : '//div[@class="timeline"]/table[@class="tweet"] | //div[@class="user-list"]/table[@class="user-item"]'
,exampleUrl : 'https://mobile.twitter.com/ https://mobile.twitter.com/search?q=css'
},
];
var MICROFORMAT = [
{
url : '^https?://.*',
nextLink : '//a[@rel="next"] | //link[@rel="next"]',
pageElement : '//*[contains(@class, "autopagerize_page_element")]',
insertBefore: '//*[contains(@class, "autopagerize_insert_before")]',
}
];
var SITEINFO_IMPORT_URLS = Config.ORIGINAL_SITEINFO ? [
'http://wedata.net/databases/AutoPagerize/items.json',
] : [];
// Super_preloaderPlus 规则更新地址
// var SITEINFO_CN_IMPORT_URL = "https://greasyfork.org/scripts/293-super-preloaderplus-one/code/Super_preloaderPlus_one.user.js";
var SITEINFO_CN_IMPORT_URL = "https://github.com/ywzhaiqi/userscript/raw/master/Super_preloaderPlus/super_preloaderplus_one.user.js";
var COLOR = {
on: '#0f0',
off: '#ccc',
enable: '#0f0',
disable: '#ccc',
loading: '#0ff',
terminated: '#00f',
error: '#f0f'
};
// 以下 設定が無いときに利用する
var FORCE_TARGET_WINDOW = true;
var BASE_REMAIN_HEIGHT = 400;
var DEBUG = false;
var AUTO_START = true;
var SCROLL_ONLY = false;
var CACHE_EXPIRE = 24 * 60 * 60 * 1000;
var XHR_TIMEOUT = 30 * 1000;
// By lastDream2013
// 出在自动翻页信息附加显示真实相对页面信息,一般能智能识别出来。如果还有站点不能识别,可以把地址的特征字符串加到下面
// 最好不要乱加,一些不规律的站点显示出来的数字也没有意义
var REALPAGE_SITE_PATTERN = ['search?', 'search_', 'forum', 'thread'];
// 自造简化版 underscroe 库,仅 ECMAScript 5
var _ = (function(){
var nativeIsArray = Array.isArray;
var _ = function(obj){
if(obj instanceof _) return obj;
if(!(this instanceof _)) return new _(obj);
this._wrapped = obj;
};
var toString = Object.prototype.toString;
_.isArray = nativeIsArray || function(obj) {
return toString.call(obj) == '[object Array]';
};
['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'].forEach(function(name){
_['is' + name] = function(obj) {
return toString.call(obj) == '[object ' + name + ']';
};
});
// Return the first value which passes a truth test. Aliased as `detect`.
_.find = function(obj, iterator, context){
var result;
obj.some(function(value, index, array){
if(iterator.call(context, value, index, array)){
result = value;
return true;
}
});
return result;
};
return _;
})();
let { classes: Cc, interfaces: Ci, utils: Cu, results: Cr } = Components;
if (!window.Services) Cu.import("resource://gre/modules/Services.jsm");
/* library */
// 来自 User Agent Overrider 扩展
const ToolbarManager = (function() {
/**
* Remember the button position.
* This function Modity from addon-sdk file lib/sdk/widget.js, and
* function BrowserWindow.prototype._insertNodeInToolbar
*/
let layoutWidget = function(document, button, isFirstRun) {
// Add to the customization palette
let toolbox = document.getElementById('navigator-toolbox');
toolbox.palette.appendChild(button);
// Search for widget toolbar by reading toolbar's currentset attribute
let container = null;
let toolbars = document.getElementsByTagName('toolbar');
let id = button.getAttribute('id');
for (let i = 0; i < toolbars.length; i += 1) {
let toolbar = toolbars[i];
if (toolbar.getAttribute('currentset').indexOf(id) !== -1) {
container = toolbar;
}
}
// if widget isn't in any toolbar, default add it next to searchbar
if (!container) {
if (isFirstRun) {
container = document.getElementById('nav-bar');
} else {
return;
}
}
// Now retrieve a reference to the next toolbar item
// by reading currentset attribute on the toolbar
let nextNode = null;
let currentSet = container.getAttribute('currentset');
let ids = (currentSet === '__empty') ? [] : currentSet.split(',');
let idx = ids.indexOf(id);
if (idx !== -1) {
for (let i = idx; i < ids.length; i += 1) {
nextNode = document.getElementById(ids[i]);
if (nextNode) {
break;
}
}
}
// Finally insert our widget in the right toolbar and in the right position
container.insertItem(id, nextNode, null, false);
// Update DOM in order to save position
// in this toolbar. But only do this the first time we add it to the toolbar
if (ids.indexOf(id) === -1) {
container.setAttribute('currentset', container.currentSet);
document.persist(container.id, 'currentset');
}
};
let addWidget = function(window, widget, isFirstRun) {
try {
layoutWidget(window.document, widget, isFirstRun);
} catch(error) {
trace(error);
}
};
let removeWidget = function(window, widgetId) {
try {
let widget = window.document.getElementById(widgetId);
widget.parentNode.removeChild(widget);
} catch(error) {
trace(error);
}
};
let exports = {
addWidget: addWidget,
removeWidget: removeWidget,
};
return exports;
})();
/* main */
if (typeof window.uAutoPagerize != 'undefined') {
window.uAutoPagerize.destroy();
delete window.uAutoPagerize;
// 补上 siteinfo_writer 菜单
if (window.siteinfo_writer && !document.getElementById("sw-popup-menuitem")) {
var menuitem = $C("menuitem", {
id: "sw-popup-menuitem",
class: "sw-add-element",
label: "辅助定制翻页规则",
oncommand: "siteinfo_writer.show();",
});
setTimeout(function(){
document.getElementById("uAutoPagerize-popup").appendChild(menuitem);
}, 1000);
}
}
var ns = window.uAutoPagerize = {
INCLUDE_REGEXP : /./,
EXCLUDE_REGEXP : [],
MICROFORMAT : MICROFORMAT.slice(),
MY_SITEINFO : MY_SITEINFO.slice(),
SITEINFO : [],
SITEINFO_CN : [],
HashchangeSites: [], // 页面不刷新的站点,在配置文件中修改
monitorUserFile: true,
get prefs() {
delete this.prefs;
return this.prefs = Services.prefs.getBranch("uAutoPagerize.");
},
get file() {
var aFile = Services.dirsvc.get('UChrm', Ci.nsILocalFile);
aFile.appendRelativePath(DB_FOLDER);
aFile.appendRelativePath('_uAutoPagerize.js');
delete this.file;
return this.file = aFile;
},
get file_CN() {
var aFile = Services.dirsvc.get('UChrm', Ci.nsILocalFile);
aFile.appendRelativePath(DB_FOLDER);
aFile.appendRelativePath('uSuper_preloader.db.js');
delete this.file_CN;
return this.file_CN = aFile;
},
get file_DB_JSON() {
var aFile = Services.dirsvc.get('UChrm', Ci.nsILocalFile);
aFile.appendRelativePath(DB_FOLDER);
aFile.appendRelativePath('uAutoPagerize.json');
delete this.file_DB_JSON;
return this.file_DB_JSON = aFile;
},
_isModified_lastcheck: 0,
_modified: 0,
get isModified() {
let aFile = ns.file;
if(!aFile.exists() || !aFile.isFile()){
return false;
}
let now = Date.now();
if (now - this._isModified_lastcheck < 1000) {
return false;
}
this._isModified_lastcheck = now;
let lmt = aFile.lastModifiedTime;
if (this._modified != lmt) {
this._modified = lmt;
return true;
}
return false;
},
get INCLUDE() INCLUDE,
set INCLUDE(arr) {
try {
this.INCLUDE_REGEXP = arr.length > 0 ?
new RegExp(arr.map(wildcardToRegExpStr).join("|")) :
/./;
INCLUDE = arr;
} catch (e) {
log("INCLUDE 不正确");
}
return arr;
},
get EXCLUDE() EXCLUDE,
set EXCLUDE(arr) {
try {
this.EXCLUDE_REGEXP = arr.map(function(s){
return new RegExp(wildcardToRegExpStr(s));
});
EXCLUDE = arr;
} catch (e) {
log("EXCLUDE 不正确");
}
return arr;
},
get AUTO_START() AUTO_START,
set AUTO_START(bool) {
updateIcon();
$("uAutoPagerize-AUTOSTART").setAttribute("checked", !!bool);
return AUTO_START = !!bool;
},
get BASE_REMAIN_HEIGHT() BASE_REMAIN_HEIGHT,
set BASE_REMAIN_HEIGHT(num) {
num = parseInt(num, 10);
if (!num) return num;
let m = $("uAutoPagerize-BASE_REMAIN_HEIGHT");
if (m) m.setAttribute("tooltiptext", BASE_REMAIN_HEIGHT = num);
return num;
},
get MAX_PAGER_NUM() Config.MAX_PAGER_NUM,
set MAX_PAGER_NUM(num) {
num = parseInt(num, 10);
if (!num) return num;
let m = $("uAutoPagerize-MAX_PAGER_NUM");
if (m) m.setAttribute("tooltiptext", Config.MAX_PAGER_NUM = num);
return num;
},
get IMMEDIATELY_PAGER_NUM() $("uAutoPagerize-immedialate-pages").value,
set IMMEDIATELY_PAGER_NUM(num){
num = parseInt(num, 10);
if (!num && (num != 0)) return num;
let m = $("uAutoPagerize-immedialate-pages");
if (m) m.value = num;
return num;
},
get DEBUG() DEBUG,
set DEBUG(bool) {
let m = $("uAutoPagerize-DEBUG");
if (m) m.setAttribute("checked", DEBUG = !!bool);
return bool;
},
get FORCE_TARGET_WINDOW() FORCE_TARGET_WINDOW,
set FORCE_TARGET_WINDOW(bool) {
let m = $("uAutoPagerize-FORCE_TARGET_WINDOW");
if (m) m.setAttribute("checked", FORCE_TARGET_WINDOW = !!bool);
return bool;
},
get SCROLL_ONLY() SCROLL_ONLY,
set SCROLL_ONLY(bool) {
let m = $("uAutoPagerize-SCROLL_ONLY");
if (m) m.setAttribute("checked", SCROLL_ONLY = !!bool);
return bool;
},
get PRELOADER_NEXTPAGE() Config.PRELOADER_NEXTPAGE,
set PRELOADER_NEXTPAGE(bool) {
let m = $("uAutoPagerize-PRELOADER_NEXTPAGE");
if (m) m.setAttribute("checked", Config.PRELOADER_NEXTPAGE = !!bool);
return bool;
},
get ADD_TO_HISTORY() Config.ADD_TO_HISTORY,
set ADD_TO_HISTORY(bool) {
let m = $("uAutoPagerize-ADD_TO_HISTORY");
if (m) m.setAttribute("checked", Config.ADD_TO_HISTORY = !!bool);
return bool;
},
lastCheckTime: 0,
setLastCheckTime: function() {
var time = parseInt(Date.now()/1000);
try {
ns.prefs.setIntPref('lastCheckTime', ns.lastCheckTime = time);
} catch(e) {}
},
init: function() {
ns.style = addStyle(css);
if (Config.isUrlbar) {
ns.icon = $('urlbar-icons').appendChild($C("image", {
id: "uAutoPagerize-icon",
state: "disable",
tooltiptext: "disable",
onclick: "if (event.button != 2) uAutoPagerize.iconClick(event);",
context: "uAutoPagerize-popup",
style: "padding: 0px 2px;",
}));
} else {
let button = $C('toolbarbutton', {
id: "uAutoPagerize-icon",
class: 'toolbarbutton-1 chromeclass-toolbar-additional',
state: "disable",
tooltiptext: "disable",
onclick: "if (event.button != 2) uAutoPagerize.iconClick(event);",
context: "uAutoPagerize-popup",
});
ToolbarManager.addWidget(window, button, false);
ns.icon = button;
}
var xml = '\
<menupopup id="uAutoPagerize-popup" position="after_start"\
ignorekeys="true"\
onpopupshowing="uAutoPagerize.onPopupShowing(event);" >\
<menuitem label="启用自动翻页"\
id="uAutoPagerize-AUTOSTART"\
type="checkbox"\
checked="'+ AUTO_START +'"\
oncommand="uAutoPagerize.toggle(event);"/>\
<menuitem label="载入/编辑配置"\
tooltiptext="左键载入配置,右键编辑配置文件和中文规则文件"\
onclick="uAutoPagerize.reloadMenuClick(event);"/>\
<menuitem label="更新中文规则" \
tooltiptext="包含 Super_preloader 的中文规则"\
oncommand="uAutoPagerize.resetSITEINFO_CN();"/>\
<menuitem label="更新原版规则" hidden="' + !Config.ORIGINAL_SITEINFO + '" \
tooltiptext="原版 JSON 规则,以外国网站为主" \
oncommand="uAutoPagerize.resetSITEINFO();"/>\
<hbox>\
<textbox id="uAutoPagerize-blacklist-textbox" oninput="uAutoPagerize.checkUrl(event);"\
tooltiptext="绿色代表在黑名单中,红色代表不匹配当前网址"/>\
<toolbarbutton label="添加" id="uAutoPagerize-blacklist-icon" \
tooltiptext="添加到黑名单" onclick="uAutoPagerize.blacklistBtnClick(event);"/>\
</hbox>\
<hbox style="padding-left:32px;">\
立即翻<textbox type="number" value="' + Config.IMMEDIATELY_PAGER_NUM + '" tooltiptext="连续翻页的数量" \
id="uAutoPagerize-immedialate-pages" style="width:35px" />页\
<toolbarbutton label="开始" tooltiptext="现在立即开始连续翻页" \
id="uAutoPagerize-immedialate-start" oncommand="uAutoPagerize.immediatelyStart();"/>\
</hbox>\
<menuseparator/>\
<menuitem label="提前预读下一页"\
tooltiptext="翻完第1页,立马预读第2页,翻完第2页,立马预读第3页..(大幅加快翻页快感-_-!!)"\
id="uAutoPagerize-PRELOADER_NEXTPAGE"\
type="checkbox"\
autoCheck="false"\
checked="'+ Config.PRELOADER_NEXTPAGE +'"\
oncommand="uAutoPagerize.PRELOADER_NEXTPAGE = !uAutoPagerize.PRELOADER_NEXTPAGE;"/>\
<menuitem label="添加下一页到历史记录"\
id="uAutoPagerize-ADD_TO_HISTORY"\
type="checkbox"\
autoCheck="false"\
checked="'+ Config.ADD_TO_HISTORY +'"\
oncommand="uAutoPagerize.ADD_TO_HISTORY = !uAutoPagerize.ADD_TO_HISTORY;"/>\
<menuitem label="新标签打开链接"\
tooltiptext="下一页的链接设置成在新标签页打开"\
id="uAutoPagerize-FORCE_TARGET_WINDOW"\
type="checkbox"\
autoCheck="false"\
checked="'+ FORCE_TARGET_WINDOW +'"\
oncommand="uAutoPagerize.FORCE_TARGET_WINDOW = !uAutoPagerize.FORCE_TARGET_WINDOW;"/>\
<menuitem label="设置翻页高度"\
id="uAutoPagerize-BASE_REMAIN_HEIGHT"\
tooltiptext="'+ BASE_REMAIN_HEIGHT +'"\
oncommand="uAutoPagerize.BASE_REMAIN_HEIGHT = prompt(\'\', uAutoPagerize.BASE_REMAIN_HEIGHT);"/>\
<menuitem label="设置最大自动翻页数"\
id="uAutoPagerize-MAX_PAGER_NUM"\
tooltiptext="'+ Config.MAX_PAGER_NUM +'"\
oncommand="uAutoPagerize.MAX_PAGER_NUM = prompt(\'\', uAutoPagerize.MAX_PAGER_NUM);"/>\
<menuitem label="滚动时才翻页"\
id="uAutoPagerize-SCROLL_ONLY"\
type="checkbox"\
autoCheck="false"\
checked="'+ SCROLL_ONLY +'"\
oncommand="uAutoPagerize.SCROLL_ONLY = !uAutoPagerize.SCROLL_ONLY;"/>\
<menuitem label="调试模式"\
id="uAutoPagerize-DEBUG"\
type="checkbox"\
autoCheck="false"\
checked="'+ DEBUG +'"\
oncommand="uAutoPagerize.DEBUG = !uAutoPagerize.DEBUG;"/>\
<menuseparator/>\
<menuitem label="首选项"\
id="uAutoPagerize-pref"\
oncommand="uAutoPagerize.openPref()"/>\
<menuitem label="在线搜索翻页规则"\
id="uAutoPagerize-search"\
oncommand="uAutoPagerize.search()"/>\
<menuitem label="打开规则列表"\
hidden="true"\
oncommand="uAutoPagerize.showUI()"/>\
</menupopup>\
';
var range = document.createRange();
range.selectNodeContents($('mainPopupSet'));
range.collapse(false);
range.insertNode(range.createContextualFragment(xml.replace(/\n|\t/g, '')));
range.detach();
["DEBUG", "AUTO_START", "FORCE_TARGET_WINDOW", "SCROLL_ONLY", "PRELOADER_NEXTPAGE", "ADD_TO_HISTORY",
"monitorUserFile"].forEach(function(name) {
try {
ns[name] = ns.prefs.getBoolPref(name);
} catch (e) {
ns.prefs.clearUserPref(name);
ns.prefs.setBoolPref(name, ns[name]);
}
}, ns);
["BASE_REMAIN_HEIGHT", "MAX_PAGER_NUM", "IMMEDIATELY_PAGER_NUM", "lastCheckTime"].forEach(function(name) {
try {
ns[name] = ns.prefs.getIntPref(name);
} catch (e) {}
}, ns);
// 载入存储的文件夹位置
try {
DB_FOLDER = ns.prefs.getCharPref('DB_FOLDER');
} catch(e) {}
ns.INCLUDE = INCLUDE;
ns.loadExclude();
ns.addListener();
ns.loadSetting();
if(!ns.loadSetting_CN()){
requestSITEINFO_CN();
} else { // 检查是否更新规则
if (Config.UPDATE_CN_SITEINFO_DAYS > 0 &&
(Date.now() - ns.lastCheckTime * 1000) > Config.UPDATE_CN_SITEINFO_DAYS * 24 * 3600 * 1000) {
requestSITEINFO_CN();
}
}
if (!getCache()){
requestSITEINFO();
}
updateIcon();
// 载入初始值
ns.isModified;
},
uninit: function() {
ns.removeListener();
["DEBUG", "AUTO_START", "FORCE_TARGET_WINDOW", "SCROLL_ONLY", "PRELOADER_NEXTPAGE", "ADD_TO_HISTORY"].forEach(function(name) {
try {
ns.prefs.setBoolPref(name, ns[name]);
} catch (e) {}
}, ns);
["BASE_REMAIN_HEIGHT", "MAX_PAGER_NUM", "IMMEDIATELY_PAGER_NUM"].forEach(function(name) {
try {
ns.prefs.setIntPref(name, ns[name]);
} catch (e) {}
}, ns);
ns.saveExclude();
ns.IMMEDIATELY_PAGER_NUM = $("uAutoPagerize-immedialate-pages").value;
},
theEnd: function() {
var ids = ["uAutoPagerize-icon", "uAutoPagerize-popup"];
for (let [, id] in Iterator(ids)) {
let e = document.getElementById(id);
if (e) e.parentNode.removeChild(e);
}
ns.style.parentNode.removeChild(ns.style);
ns.removeListener();
},
destroy: function() {
ns.uninit();
ns.theEnd();
},
addListener: function() {
gBrowser.mPanelContainer.addEventListener('DOMContentLoaded', this, true);
gBrowser.mTabContainer.addEventListener('TabSelect', this, false);
gBrowser.mTabContainer.addEventListener('TabClose', this, false);
window.addEventListener('uAutoPagerize_destroy', this, false);
window.addEventListener('unload', this, false);
// uc 脚本会因为打开新窗口而重复注册
var mediator = Cc["@mozilla.org/appshell/window-mediator;1"]
.getService(Ci.nsIWindowMediator);
var enumerator = mediator.getEnumerator("navigator:browser");
while (enumerator.hasMoreElements()) {
var win = enumerator.getNext();
if (win.uAutoPagerize && win.uAutoPagerize.registerDone) {
return;
}
}
ns.prefs.addObserver('', this, false);
ns.registerDone = true;
},
removeListener: function() {
gBrowser.mPanelContainer.removeEventListener('DOMContentLoaded', this, true);
gBrowser.mTabContainer.removeEventListener('TabSelect', this, false);
gBrowser.mTabContainer.removeEventListener('TabClose', this, false);
window.removeEventListener('uAutoPagerize_destroy', this, false);
window.removeEventListener('unload', this, false);
if (ns.registerDone) {
ns.prefs.removeObserver('', this, false);
ns.registerDone = false;
}
},
handleEvent: function(event) {
switch(event.type) {
case "DOMContentLoaded":
if (this.AUTO_START)
this.launch(event.target.defaultView, null, true);
break;
case "TabSelect":
if (this.AUTO_START)
updateIcon();
break;
case "TabClose": // 如果有 iframe 则移除
let browser = gBrowser.getBrowserForTab(event.target);
if(browser.uAutoPagerizeIframes){
browser.uAutoPagerizeIframes.forEach(function(i){
i.parentNode.removeChild(i);
});
browser.uAutoPagerizeIframes = null
}
break;
case "uAutoPagerize_destroy":
this.destroy(event);
break;
case "unload":
this.uninit(event);
break;
}
},
observe: function(aSubject, aTopic, aData){
if (aTopic == 'nsPref:changed') {
switch(aData) {
case 'EXCLUDE':
ns.loadExclude();
break;
case 'monitorUserFile':
this.monitorUserFile = this.prefs.getBoolPref('monitorUserFile');
break;
}
}
},
loadExclude: function() {
// 从 prefs 载入 EXCLUDE
try{
let str = ns.prefs.getCharPref("EXCLUDE");
ns.EXCLUDE = str.split(/,| |[\n\r]+/);
}catch(e){}
if(!ns.EXCLUDE){
ns.EXCLUDE = EXCLUDE;
}
},
saveExclude: function() { // 保存到 about:config 中
ns.prefs.setCharPref("EXCLUDE", ns.EXCLUDE.join("\n"));
},
loadSetting: function(isAlert) {
var data = loadText(ns.file);
if (!data) return false;
var sandbox = new Cu.Sandbox( new XPCNativeWrapper(window) );
sandbox.INCLUDE = null;
// sandbox.EXCLUDE = null;
sandbox.MY_SITEINFO = [];
sandbox.MICROFORMAT = [];
sandbox.USE_MY_SITEINFO = false;
sandbox.USE_MICROFORMAT = true;
data = ns.convertSiteInfoData(data);
try {
var lineFinder = new Error();
Cu.evalInSandbox(data, sandbox, '1.8');
} catch (e) {
let line = e.lineNumber - lineFinder.lineNumber -1;
alerts("uAutoPagerize", e + "\n请重新检查配置文件第 " + line + " 行", function(){
ns.edit(ns.file, line);
});
log('load error.', e);
return;
}
sandbox.MY_SITEINFO = ns.convertSiteInfos(sandbox.MY_SITEINFO);
ns.MY_SITEINFO = sandbox.USE_MY_SITEINFO ? sandbox.MY_SITEINFO.concat(MY_SITEINFO): sandbox.MY_SITEINFO;
ns.MICROFORMAT = sandbox.USE_MICROFORMAT ? sandbox.MICROFORMAT.concat(MICROFORMAT): sandbox.MICROFORMAT;
if (sandbox.INCLUDE)
ns.INCLUDE = sandbox.INCLUDE;
// if (sandbox.EXCLUDE)
// ns.EXCLUDE = sandbox.EXCLUDE;
var newPrefs = sandbox.prefs;
if (newPrefs) {
Object.keys(newPrefs).forEach(function(key){
prefs[key] = newPrefs[key];
});
}
if (sandbox.HashchangeSites)
ns.HashchangeSites = sandbox.HashchangeSites;
if (isAlert) alerts('uAutoPagerize', '配置文件已经重新载入');
return true;
},
loadSetting_CN: function(isAlert) {
var data = loadText(ns.file_CN);
if (!data) return false;
var sandbox = new Cu.Sandbox( new XPCNativeWrapper(window) );
sandbox.SITEINFO = [];
sandbox.SITEINFO_TP = [];
sandbox.SITEINFO_comp = [];
data = ns.convertSiteInfoData(data);
try {
Cu.evalInSandbox(data, sandbox, '1.8');
} catch (e) {
return log('载入中文数据库错误', e);
}
var list = sandbox.SITEINFO.concat(sandbox.SITEINFO_TP).concat(sandbox.SITEINFO_comp);
ns.SITEINFO_CN = ns.convertSiteInfos(list);
if (isAlert)
alerts('uAutoPagerize', '中文数据库已经重新载入');
return true;
},
convertSiteInfoData: function(data) {
// 替换 window、document、unsafeWindow、console
return data.replace(/((?:document|start)?Filter:\s*function\s*\(.*\)\s*\{.*)/ig,
"$1 var window = this, document = this.document, unsafeWindow = this.wrappedJSObject, " +
"console = this.console;");
},
convertSiteInfos: function(list) {
var newList = [];
// 转换
for(let [index, info] in Iterator(list)){
if (!info.autopager){
newList.push(info);
continue;
}
let newInfo = {
url: info.url,
nextLink: info.nextLink,
pageElement: info.pageElement,
name: info.name || info.siteName,
exampleUrl: info.exampleUrl || info.siteExample
};
['name', 'exampleUrl'].forEach(function(n){
if (!newInfo[n]) delete newInfo[n];
});
["enable", "pageElement", "useiframe", "newIframe", "iloaded", "itimeout", "documentFilter", "filter",
"startFilter", "stylish", 'replaceE', 'lazyImgSrc', 'separatorReal', 'maxpage', 'ipages'].forEach(function(name){
if(info.autopager[name] != undefined){
newInfo[name] = info.autopager[name];
}
});
if (newInfo.ipages == undefined) {
newInfo.ipages = prefs.ipages;
}
newList.push(newInfo);
}
return newList;
},
launch: function(win, timer, DOMLoad){
if (!win) return;
var doc = win.document;
if (!doc) return;
// 监测文件是否更新
if (ns.monitorUserFile && ns.isModified){
ns.loadSetting(true);
}
var locationHref = win.location.href,
locationHost = win.location.host;
if (locationHref.indexOf('http') !== 0 ||
!ns.INCLUDE_REGEXP.test(locationHref)){
return updateIcon("不包含的页面");
}
if (!/html|xml/i.test(doc.contentType) ||
doc.body instanceof HTMLFrameSetElement ||
win.frameElement && !(win.frameElement instanceof HTMLFrameElement) ||
doc.querySelector('meta[http-equiv="refresh"]') && /shooter\.cn/.test(win.location.host))
return updateIcon();
if (typeof win.AutoPagerize == 'undefined') {
win.filters = [];
win.documentFilters = [];
win.requestFilters = [];
win.responseFilters = [];
win.AutoPagerize = {
addFilter : function(f) { win.filters.push(f) },
addDocumentFilter : function(f) { win.documentFilters.push(f); },
addResponseFilter : function(f) { win.responseFilters.push(f); },
addRequestFilter : function(f) { win.requestFilters.push(f); },
launchAutoPager : function(l) { launchAutoPager_org(l, win); }
}
// uAutoPagerize original
win.fragmentFilters = [];
}
for(let [index, reg] in Iterator(ns.EXCLUDE_REGEXP)){
if(reg.test(locationHref)){
return updateIcon("排除列表, " + ns.EXCLUDE[index]);
}
}
var ev = doc.createEvent('Event');
ev.initEvent('GM_AutoPagerizeLoaded', true, false);
doc.dispatchEvent(ev);
var miscellaneous = [];
// 継ぎ足されたページからは新しいタブで開く
win.fragmentFilters.push(function(df){
if (!ns.FORCE_TARGET_WINDOW) return;
var arr = Array.slice(df.querySelectorAll('a[href]:not([href^="mailto:"]):not([href^="javascript:"]):not([href^="#"])'));
arr.forEach(function (elem){
elem.setAttribute('target', '_blank');
if (elem.getAttribute('onclick') == 'atarget(this)') { // 卡饭论坛的控制是否在新标签页打开
elem.removeAttribute('onclick');
}
});
});
var index = -1, info, nextLink;
var hashchange = false;
function reStartAutoPager() {
debug("触发 Hashchang 或 pjax:success 事件" + locationHref);
if (!win.ap) {
win.setTimeout(function(){
let [index, info] = [-1, null];
if (!info) [, info] = ns.getInfo(ns.MY_SITEINFO, win);
if (!info) [, info] = ns.getInfo(null, win);
if (info) win.ap = new AutoPager(win.document, info);
updateIcon();
}, timer);
return;
}
let info = win.ap.info;
win.ap.destroy(true);
win.setTimeout(function(){
win.ap = new AutoPager(win.document, info);
updateIcon();
}, timer);
}
// 页面不刷新的站点
var hashSite = _.find(ns.HashchangeSites, function(x){ return toRE(x.url).test(locationHref); });
if (hashSite) {
timer = hashSite.timer;
hashchange = true;
debug('当前是页面不刷新的站点');
} else if (locationHost == 'github.com' && Services.appinfo.version < 33) {
// github 需要在加载页面后重新启用
// 直接引用 unsafeWindow.jQuery 的方式无法成功,只能采用下面的方式。
var github_addListener = function(win){
var script = '\
(function(){\
var $ = unsafeWindow.jQuery;\
if(!$) return;\
$(document).on("pjax:success", function(){\
run();\
});\
})();\
';
let sandbox = new Cu.Sandbox(win, {sandboxPrototype: win});
sandbox.unsafeWindow = win.wrappedJSObject;
sandbox.document = win.document;
sandbox.window = win;
sandbox.run = reStartAutoPager;
Cu.evalInSandbox(script, sandbox);
};
github_addListener(win);
debug('github.com 成功添加 pjax:success 事件')
}
if(hashchange){
win.addEventListener("hashchange", reStartAutoPager, false);
}
// 不是加载文档时启用则不需要延迟
if (!DOMLoad) {
timer = 0;
}
win.setTimeout(function(){
var startTime = Date.now();
win.ap = null;
miscellaneous.forEach(function(func){ func(doc, locationHref); });
var index = -1;
if (!info) [, info, nextLink] = ns.getInfo(ns.MY_SITEINFO, win);
if (!info) [, info, nextLink] = ns.getInfo(ns.SITEINFO_CN, win);
if (info) {
if (info.requestFilter)
win.requestFilters.push(info.requestFilter.bind(win));
if (info.responseFilter)
win.responseFilters.push(info.responseFilter.bind(win));
if (info.documentFilter)
win.documentFilters.push(info.documentFilter.bind(win));
if (info.filter && typeof(info.filter) === "function")
win.filters.push(info.filter.bind(win));
if (info.fragmentFilter)
win.fragmentFilters.push(info.fragmentFilter.bind(win));
if (info.stylish) {
let style = doc.createElement("style");
style.setAttribute("id", "uAutoPagerize-style");
style.setAttribute("type", "text/css");
style.appendChild(doc.createTextNode(info.stylish));
doc.getElementsByTagName("head")[0].appendChild(style);
}
}
//var s = Date.now();
if (!info) [, info, nextLink] = ns.getInfo(ns.SITEINFO, win);
//debug(index + 'th/' + (Date.now() - s) + 'ms');
if (!info) [, info, nextLink] = ns.getInfo(ns.MICROFORMAT, win);
if (info) {
if (info.enable === false) {
debug('找到规则:', info, '但默认禁用');
updateIcon("找到规则,但默认禁用");
} else {
win.ap = new AutoPager(win.document, info, nextLink);
}
}
debug('总耗时:' + (new Date() - startTime) + '毫秒, 地址为:' + locationHref);
updateIcon();
}, timer||0);