东方永页机

自动加载并拼接下一分页内容(适用于论坛、漫画站、小说站、资讯站、博客等),无需规则支持所有网页

当前为 2022-03-05 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Pagetual
  3. // @name:zh-CN 东方永页机
  4. // @name:zh-TW 東方永頁機
  5. // @name:ja 東方永頁機
  6. // @name:ru Пейджетуал
  7. // @name:de Pagetual
  8. // @name:es Pagetual
  9. // @name:fr Pagetual
  10. // @name:it Pagetual
  11. // @name:ko 東方永頁機
  12. // @namespace hoothin
  13. // @version 1.5.3.8
  14. // @description Most compatible Auto pager script ever! Simply auto loading paginated web pages.
  15. // @description:zh-CN 自动加载并拼接下一分页内容(适用于论坛、漫画站、小说站、资讯站、博客等),无需规则支持所有网页
  16. // @description:zh-TW 自動加載並拼接下一分頁內容(適用於論壇、漫畫站、小說站、資訊站、博客等),無需規則支持所有網頁
  17. // @description:ja Webページを自動で読み込み継ぎ足し表示を行うブラウザ拡張です
  18. // @description:ru Просто автоматически загрузите следующую страницу
  19. // @description:de Laden Sie einfach automatisch die nächste Seite
  20. // @description:es Carga automática de páginas web paginadas
  21. // @description:fr Chargement automatique des pages Web paginées
  22. // @description:it Caricamento automatico di pagine Web impaginate
  23. // @description:ko 다음 페이지를 자동으로 로드하세요
  24. // @author hoothin
  25. // @include http://*
  26. // @include https://*
  27. // @license MIT
  28. // @icon data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAdVBMVEUAAAD3VU33VU32VEz8U073VU32VU33VU32VUz0Uk/3VE32VU32VUz2VU32VU32VU32VU33VU33U0z2VU34Wkv3VE32VUz/mpj/nJj2VUz2VU32VE33VEz2VU32VU32VUz3VE32VEz3VE3/mZf2Vkz2VU3/mpilFFolAAAAJXRSTlMA3Lp/GvTBT5YQLuawZ/DOyZwlPQeKc21N04+FX1bqpm9DNoB4T68ePwAAAitJREFUWMPt1tuasiAUBuCFCG5Rs3QybTPV1/1f4v/3PDkyIojn8x5qBrI+ltAfh32/yysmBKvyXb+njb6bDL9kzTd5SzjDAsYT8nFoGSxYe6BVqoNDp2jFDit25BRgVUAODB4YWcETWVTwVNGiGN5iWtBgg4YMCpsoI38dNunmmWyxUTvbPwwbsYR0fIzZLQ0pTG8eieRmBLMmpdH9uimQEf6TNRnXXKLZHixpJtywLzOgMHtFCqdM64DahHRnOE1dsrekm9wr2WtLcAlpdHwcp1pAJySXYnERclzp4+v19jXdmcTvQUJtz+ZaI4i05/V/UGYrCxbaAsOYoNfIKEQxpqQuzCgJJJ/3f42O8ywEZuMVWi/8hODxGj3GW2b0udkbGULLDOjimAG0S3fLGlBnXQM9irG1CiQdVQi0dqQsOSDlyEEz7Vy9OxxfR71VCXsSB23jMrKJYZXSjw57sqgLn5Z0wolsOCz0RyJkyeYjgz7pwwVq20eboZwtVUl2EnN5gJ50dQZFdryATvABRTr/tJXkUMdaAK5pwtCapwtFLskguwuyMh/Sd9WChQ4sIvIUYSk3PYqQvCQlOC04IfN7PkdjOyRKWhdKXMmiAFt9i3sJ5jxoRuR0vqAghxxwHuqfQE5OHGDKOrwEnqs1DgAZ2e4Eev1d45TN7JfhrQLKgfwMFYAsvp33dXII073aVQLI2gN5S58lfmGnKKFtah7nkgnBZB7zlP7Y/QNiTM6sYNzawwAAAABJRU5ErkJggg==
  29. // @grant GM_xmlhttpRequest
  30. // @grant GM_registerMenuCommand
  31. // @grant GM_notification
  32. // @grant GM_getValue
  33. // @grant GM_setValue
  34. // @grant GM_addStyle
  35. // @grant GM_openInTab
  36. // @grant GM_deleteValue
  37. // @grant GM.xmlHttpRequest
  38. // @grant GM.registerMenuCommand
  39. // @grant GM.notification
  40. // @grant GM.getValue
  41. // @grant GM.setValue
  42. // @grant GM.addStyle
  43. // @grant GM.openInTab
  44. // @grant GM.deleteValue
  45. // @supportURL https://github.com/hoothin/UserScripts/issues
  46. // @connect wedata.net
  47. // @connect githubusercontent.com
  48. // @run-at document-idle
  49. // @exclude http://www.toodledo.com/tasks/*
  50. // @exclude http*://maps.google.com*/*
  51. // @exclude *://www.google.*/_/chrome/newtab*
  52. // @exclude *://mega.*/*
  53. // @exclude *://*.mega.*/*
  54. // @exclude *://*.youku.com/v_*
  55. // @exclude *://*pan.baidu.com
  56. // @exclude *://*.iqiyi.com/v_*
  57. // @exclude *://*.iqiyi.com/w_*
  58. // @exclude *://*.iqiyi.com/a_*
  59. // @exclude *://*.le.com/ptv/vplay/*
  60. // @exclude *://v.qq.com/x/cover/*
  61. // @exclude *://v.qq.com/x/page/*
  62. // @exclude *://v.qq.com/tv/*
  63. // @exclude *://*.tudou.com/listplay/*
  64. // @exclude *://*.tudou.com/albumplay/*
  65. // @exclude *://*.tudou.com/programs/view/*
  66. // @exclude *://*.mgtv.com/b/*
  67. // @exclude *://film.sohu.com/album/*
  68. // @exclude *://tv.sohu.com/v/*
  69. // @exclude *://*.bilibili.com/video/*
  70. // @exclude *://*.bilibili.com/bangumi/play/*
  71. // @exclude *://*.baofeng.com/play/*
  72. // @exclude *://vip.pptv.com/show/*
  73. // @exclude *://v.pptv.com/show/*
  74. // @exclude *://www.le.com/ptv/vplay/*
  75. // @exclude *://www.wasu.cn/Play/show/*
  76. // @exclude *://m.v.qq.com/*
  77. // @exclude *://m.iqiyi.com/*
  78. // @exclude *://m.youku.com/alipay_video/*
  79. // @exclude *://m.mgtv.com/b/*
  80. // @exclude *://m.tv.sohu.com/v/*
  81. // @exclude *://m.film.sohu.com/album/*
  82. // @exclude *://m.le.com/ptv/vplay/*
  83. // @exclude *://m.pptv.com/show/*
  84. // @exclude *://m.acfun.cn/v/*
  85. // @exclude *://m.bilibili.com/video/*
  86. // @exclude *://m.bilibili.com/anime/*
  87. // @exclude *://m.bilibili.com/bangumi/play/*
  88. // @exclude *://m.wasu.cn/Play/show/*
  89. // @exclude *://www.youtube.com
  90. // @exclude *://www.youtube.com/
  91. // @exclude *://www.youtube.com/watch*
  92. // @exclude *://baike.baidu.com/*
  93. // @exclude *://*.instagram.com/*
  94. // @exclude *://order.jd.com/*
  95. // @exclude *://pagetual.hoothin.com/*
  96. // @exclude *://hoothin.github.io/PagetualGuide/*
  97. // @connect *
  98. // ==/UserScript==
  99.  
  100. (function() {
  101. 'use strict';
  102.  
  103. if (window.name === 'pagetual-iframe') {
  104. var domloaded = function (){
  105. window.scroll(window.scrollX, 999999);
  106. //window.parent.postMessage('pagetual-iframe:DOMLoaded', '*');
  107. };
  108. if(window.opera){
  109. document.addEventListener('DOMContentLoaded', domloaded, false);
  110. } else {
  111. domloaded();
  112. }
  113. return;
  114. }
  115.  
  116. if(window.top != window.self){
  117. try{
  118. if (top.location.hostname != window.location.hostname) {
  119. return;
  120. }
  121. }catch(e){
  122. return;
  123. }
  124. }
  125.  
  126. const lang = navigator.appName=="Netscape"?navigator.language:navigator.userLanguage;
  127. var i18n=(name, param)=>{
  128. let config={};
  129. switch (lang){
  130. case "zh-CN":
  131. case "zh-SG":
  132. config={
  133. enableDebug:"调试模式",
  134. disable:"暂时禁用",
  135. disableSite:"在此站禁用",
  136. enable:"启用翻页",
  137. toTop:"回到顶部",
  138. toBottom:"前往页尾",
  139. current:"当前页",
  140. forceIframe:"强制拼接",
  141. cancelForceIframe:"取消强制拼接",
  142. configure:"打开配置页",
  143. firstUpdate:"点击此处初始化规则",
  144. update:"更新规则",
  145. click2update:"点击立即更新规则",
  146. loadNow:"立即翻页",
  147. loadConfirm:"要翻几页?(0为不间断)",
  148. noNext:"没有找到下一页,请新建规则",
  149. passSec:"更新于 #t# 秒前",
  150. passMin:"更新于 #t# 分钟前",
  151. passHour:"更新于 #t# 小时前",
  152. passDay:"更新于 #t# 天前",
  153. cantDel:"无法删除内置规则",
  154. confirmDel:"是否确认要删除此规则?",
  155. updateSucc:"更新成功",
  156. beginUpdate:"正在更新,请稍候",
  157. customUrls:"导入规则url,一行一条,AutoPagerize 格式规则需要以\"0|\"开头",
  158. customRules:"输入【东方永页机】格式的自定义规则",
  159. save:"保存设置",
  160. loadingText:"少女祈祷中...",
  161. opacity:"分页隔条不透明值",
  162. hideBar:"空白处双击隐藏分页隔条",
  163. dbClick2Stop:"空白处双击暂停翻页",
  164. sortTitle:"排序在下次更新规则后生效",
  165. autoRun:"自动启用",
  166. inputPageNum:"输入页码跳转",
  167. enableHistory:"翻页后写入历史记录",
  168. initRun:"打开页面后立即尝试翻页"
  169. };
  170. break;
  171. case "zh-TW":
  172. case "zh-HK":
  173. config={
  174. enableDebug:"調試模式",
  175. disable:"暫時禁用",
  176. disableSite:"在此站禁用",
  177. enable:"啟用翻頁",
  178. toTop:"回到頂部",
  179. toBottom:"前往頁尾",
  180. current:"當前頁",
  181. forceIframe:"強制拼接",
  182. cancelForceIframe:"取消强制拼接",
  183. configure:"打開配置頁",
  184. firstUpdate:"點擊此處初始化規則",
  185. update:"更新規則",
  186. click2update:"點擊立即更新規則",
  187. loadNow:"立即翻頁",
  188. loadConfirm:"要翻几頁?(0為不間斷)",
  189. noNext:"沒有找到下一頁,請新建規則",
  190. passSec:"更新于 #t# 秒前",
  191. passMin:"更新于 #t# 分鐘前",
  192. passHour:"更新于 #t# 小時前",
  193. passDay:"更新于 #t# 天前",
  194. cantDel:"無法刪除内置規則",
  195. confirmDel:"是否確認要刪除此規則?",
  196. updateSucc:"更新成功",
  197. beginUpdate:"正在更新,請稍候",
  198. customUrls:"導入規則url,一行一條,AutoPagerize 格式規則需要以\"0|\"開頭",
  199. customRules:"輸入【東方永頁機】格式的自定義規則",
  200. save:"存儲設置",
  201. loadingText:"少女祈禱中...",
  202. opacity:"分頁隔條不透明值",
  203. hideBar:"空白處雙擊隱藏分頁隔條",
  204. dbClick2Stop:"空白處雙擊暫停翻頁",
  205. sortTitle:"排序在下次更新規則後生效",
  206. autoRun:"自動啓用",
  207. inputPageNum:"輸入頁碼跳轉",
  208. enableHistory:"翻頁后寫入歷史記錄",
  209. initRun:"打開頁面后立即嘗試翻頁"
  210. };
  211. break;
  212. case "ja":
  213. config = {
  214. enableDebug:"デバッグモード",
  215. disable: "一時的に無効にする",
  216. disableSite:"このサイト無効",
  217. enable: "ページめくりを有効にする",
  218. toTop: "トップに戻る",
  219. toBottom: "ページの下部に移動",
  220. current: "現在のページ",
  221. forceIframe: "強制ステッチ",
  222. cancelForceIframe: "強制ステッチをキャンセル",
  223. configure: "設定ページを開く",
  224. firstUpdate:"ここをクリックしてルールを初期化します",
  225. update: "更新ルール",
  226. click2update:"今すぐルールを更新してください",
  227. loadNow:"今すぐページをめくる",
  228. loadConfirm:"数ページめくりたいですか?(0は途切れない)",
  229. noNext:"次のページが見つかりません、新しいルールを作成してください",
  230. passSec: "#t#秒前に更新",
  231. passMin: "#t#分前に更新",
  232. passHour: "#t#時間前に更新",
  233. passDay: "#t#日前に更新",
  234. cantDel: "組み込みルールを削除できません",
  235. confirmDel: "このルールを削除してもよろしいですか?",
  236. updateSucc: "更新に成功しました",
  237. beginUpdate: "更新中、お待ちください",
  238. customUrls: "インポートルールのURL、1行に1つ、AutoPagerizeフォーマットルールは\"0|\"で始まる必要があります",
  239. customRules: "【東方永頁機】の形式でカスタムルールを入力してください",
  240. save: "設定を保存",
  241. loadingText: "少女祈祷中...",
  242. opacity:"ページネーションバーの不透明値",
  243. hideBar:"空白部分をダブルクリックして、ページ区切り文字を非表示にします",
  244. dbClick2Stop:"空白部分をダブルクリックしてページめくりを一時停止します",
  245. sortTitle:"並べ替えは、次のルールの更新後に有効になります",
  246. autoRun:"自動的に有効",
  247. inputPageNum:"ジャンプするページ番号を入力",
  248. enableHistory:"ページめくり後の履歴を書く",
  249. initRun:"Webページを開いた直後にページをめくる"
  250. };
  251. break;
  252. default:
  253. config={
  254. enableDebug:"Enable debug output",
  255. disable:"Disable",
  256. disableSite:"Disable on the site",
  257. enable:"Enable",
  258. toTop:"To Top",
  259. toBottom:"To Bottom",
  260. current:"Current Page",
  261. forceIframe:"Force to join",
  262. cancelForceIframe:"Cancel Force join",
  263. configure:"Configure",
  264. firstUpdate:"Click here to initialize the rules",
  265. update:"Update rules",
  266. click2update:"Click to update rules from url now",
  267. loadNow:"Load next now",
  268. loadConfirm:"How much pages do you want to load? (0 means infinite)",
  269. noNext:"No next link found, please create a new rule",
  270. passSec:"Updated #t# seconds ago",
  271. passMin:"Updated #t# minutes ago",
  272. passHour:"Updated #t# hours ago",
  273. passDay:"Updated #t# days ago",
  274. cantDel:"Can't delete buildin rules",
  275. confirmDel:"Are you sure you want to delete this rule?",
  276. updateSucc:"Update succeeded",
  277. beginUpdate:"Begin update, wait a minute please",
  278. customUrls:"Import rule url, One url per line, rules on AutoPagerize format need to start with \"0|\"",
  279. customRules:"Input custom rules with [Pagetual] format",
  280. save:"Save",
  281. loadingText:"Shojo Now Loading...",
  282. opacity:"Pagination spacer opacity",
  283. hideBar:"Double-click on the blank space to hide the paging spacer",
  284. dbClick2Stop:"Double-click on the blank space to stop",
  285. sortTitle:"Sorting takes effect after the next rule update",
  286. autoRun:"Auto run",
  287. inputPageNum:"Enter page number to jump",
  288. enableHistory:"Write history after page turning",
  289. initRun:"Turn pages immediately after opening"
  290. };
  291. break;
  292. }
  293. return config[name]?config[name].replace("#t#",param):name;
  294. };
  295.  
  296. var enableDebug=true;
  297. var debug=str=>{
  298. if(enableDebug){
  299. console.debug(str);
  300. }
  301. };
  302.  
  303. var _GM_xmlhttpRequest,_GM_registerMenuCommand,_GM_notification,_GM_addStyle,_GM_openInTab;
  304. if(typeof GM_xmlhttpRequest!='undefined'){
  305. _GM_xmlhttpRequest=GM_xmlhttpRequest;
  306. }else if(typeof GM!='undefined' && typeof GM.xmlHttpRequest!='undefined'){
  307. _GM_xmlhttpRequest=GM.xmlHttpRequest;
  308. }else{
  309. _GM_xmlhttpRequest=(f)=>{fetch(f.url).then(response=>response.text()).then(data=>{let res={response:data};f.onload(res)}).catch(f.onerror())};
  310. }
  311. if(typeof GM_registerMenuCommand!='undefined'){
  312. _GM_registerMenuCommand=GM_registerMenuCommand;
  313. }else if(typeof GM!='undefined' && typeof GM.registerMenuCommand!='undefined'){
  314. _GM_registerMenuCommand=GM.registerMenuCommand;
  315. }else{
  316. _GM_registerMenuCommand=(s,f)=>{};
  317. }
  318. if(typeof GM_notification!='undefined'){
  319. _GM_notification=GM_notification;
  320. }else if(typeof GM!='undefined' && typeof GM.notification!='undefined'){
  321. _GM_notification=GM.notification;
  322. }else{
  323. _GM_notification=(s)=>{alert(s)};
  324. }
  325. if(typeof GM_openInTab!='undefined'){
  326. _GM_openInTab=GM_openInTab;
  327. }else if(typeof GM!='undefined' && typeof GM.openInTab!='undefined'){
  328. _GM_openInTab=GM.openInTab;
  329. }else{
  330. _GM_openInTab=(s,t)=>{window.open(s)};
  331. }
  332. if(typeof GM_addStyle!='undefined'){
  333. _GM_addStyle=GM_addStyle;
  334. }else if(typeof GM!='undefined' && typeof GM.addStyle!='undefined'){
  335. _GM_addStyle=GM.addStyle;
  336. }else{
  337. _GM_addStyle=cssStr=>{
  338. let styleEle=document.createElement("style");
  339. styleEle.innerHTML=cssStr;
  340. document.head.appendChild(styleEle);
  341. };
  342. }
  343. var _unsafeWindow=(typeof unsafeWindow=='undefined')?window:unsafeWindow;//兼容 ios userscripts 的寫法
  344. var storage={
  345. supportGM: typeof GM_getValue=='function' && typeof GM_getValue('a','b')!='undefined',
  346. supportGMPromise: typeof GM!='undefined' && typeof GM.getValue=='function' && typeof GM.getValue('a','b')!='undefined',
  347. mxAppStorage:(function(){
  348. try{
  349. return window.external.mxGetRuntime().storage;
  350. }catch(e){
  351. }
  352. })(),
  353. operaUJSStorage:(function(){
  354. try{
  355. return window.opera.scriptStorage;
  356. }catch(e){
  357. }
  358. })(),
  359. setItem:function(key,value){
  360. if(this.operaUJSStorage){
  361. this.operaUJSStorage.setItem(key,value);
  362. }else if(this.mxAppStorage){
  363. this.mxAppStorage.setConfig(key,value);
  364. }else if(this.supportGM){
  365. GM_setValue(key,value);
  366. if(value==="" && typeof GM_deleteValue!='undefined'){
  367. GM_deleteValue(key);
  368. }
  369. }else if(this.supportGMPromise){
  370. GM.setValue(key,value);
  371. if(value==="" && typeof GM!='undefined' && typeof GM.deleteValue!='undefined'){
  372. GM.deleteValue(key);
  373. }
  374. }else if(window.localStorage){
  375. window.localStorage.setItem(key,value);
  376. }
  377. },
  378. getItem:function(key,cb){
  379. var value;
  380. if(this.operaUJSStorage){
  381. value=this.operaUJSStorage.getItem(key);
  382. }else if(this.mxAppStorage){
  383. value=this.mxAppStorage.getConfig(key);
  384. }else if(this.supportGM){
  385. value=GM_getValue(key);
  386. }else if(this.supportGMPromise){
  387. value=GM.getValue(key).then(v=>{cb(v)});
  388. return;
  389. }else if(window.localStorage){
  390. value=window.localStorage.getItem(key);
  391. };
  392. cb(value);
  393. }
  394. };
  395. var rulesData={},ruleUrls,updateDate,configPage="https://github.com/hoothin/UserScripts/tree/master/Pagetual";
  396. var allOfBody="body>*";
  397. _GM_registerMenuCommand(i18n("configure"), ()=>{
  398. _GM_openInTab(configPage,{active:true});
  399. });
  400.  
  401. function getElementByXpath(xpath, contextNode, doc){
  402. doc = doc || document;
  403. contextNode = contextNode || doc;
  404. try {
  405. var result = doc.evaluate(xpath, contextNode, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
  406. return result.singleNodeValue && result.singleNodeValue.nodeType === 1 && result.singleNodeValue;
  407. } catch (err) {
  408. throw new Error(`Invalid xpath: ${xpath}`);
  409. }
  410. }
  411.  
  412. function getAllElementsByXpath(xpath, contextNode, doc){
  413. doc = doc || document;
  414. contextNode = contextNode || doc;
  415. var result = [];
  416. try {
  417. var query = doc.evaluate(xpath, contextNode, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  418. for (var i = 0; i < query.snapshotLength; i++) {
  419. var node = query.snapshotItem(i);
  420. if (node.nodeType === 1) result.push(node);
  421. }
  422. } catch (err) {
  423. throw new Error(`Invalid xpath: ${xpath}`);
  424. }
  425. return result;
  426. }
  427.  
  428. class RuleParser {
  429. constructor() {
  430. this.hpRules=[];
  431. this.customRules=[];
  432. this.rules=[];
  433. this.pageDoc=document;
  434. this.nextLinkHref=null;
  435. this.curUrl=location.href;
  436. this.curSiteRule={};
  437. }
  438.  
  439. initSavedRules(callback){
  440. var self=this;
  441. storage.getItem("hpRules", hpRules=>{
  442. if(hpRules)self.hpRules=hpRules;
  443. storage.getItem("customRules", customRules=>{
  444. if(customRules)self.customRules=customRules;
  445. storage.getItem("rules", rules=>{
  446. if(rules)self.rules=rules;
  447. callback();
  448. });
  449. });
  450. });
  451. }
  452.  
  453. saveCurSiteRule(){
  454. if(!this.curSiteRule || !this.curSiteRule.url || this.curSiteRule.singleUrl)return;
  455. this.hpRules=this.hpRules.filter(item=>{return item&&item.url!=this.curSiteRule.url});
  456. this.hpRules.unshift(this.curSiteRule);
  457. if(this.hpRules.length>30){
  458. this.hpRules.pop();
  459. }
  460. storage.setItem("hpRules", this.hpRules);
  461. }
  462.  
  463. requestJSON(url, callback){
  464. _GM_xmlhttpRequest({
  465. url: url,
  466. method: 'GET',
  467. timeout: 20000,
  468. onload: function(res) {
  469. let json=null;
  470. try{
  471. json=JSON.parse(res.response||res.responseText);
  472. }catch(e){
  473. debug(e);
  474. }
  475. callback(json);
  476. },
  477. onerror: function(e) {
  478. callback(null, e);
  479. },
  480. ontimeout: function(e) {
  481. callback(null, e);
  482. }
  483. });
  484. }
  485.  
  486. formatRule(item, type, from){
  487. switch(type){
  488. case 0:
  489. return {
  490. from:from,
  491. type:type,
  492. name:item.name,
  493. action:item.data.forceIframe=="true"?1:0,
  494. url:item.data.url,
  495. pageElement:item.data.pageElement,
  496. nextLink:item.data.nextLink,
  497. insert:item.data.insertBefore,
  498. insertPos:1,
  499. updatedAt:item.data.updated_at,
  500. css:item.data.Stylus+item.data.CSS,
  501. pageAction:item.data.bookmarklet
  502. };
  503. break;
  504. case 1:
  505. default:
  506. item.from=from;
  507. if(typeof(item.type) == "undefined")item.type=type;
  508. return item;
  509. break;
  510. }
  511. return null;
  512. }
  513.  
  514. addRuleByUrl(url, type, from, callback) {
  515. if(url.indexOf("?")==-1){
  516. url=url+"?"+Date.now();
  517. }else{
  518. url=url+"&"+Date.now();
  519. }
  520. this.requestJSON(url, (json,err)=>{
  521. if(!json){
  522. debug("Update "+url+" rules fail!");
  523. debug(err);
  524. }
  525. this.addRules(json, type, from);
  526. callback(json, err);
  527. });
  528. }
  529.  
  530. addRules(rules, type, from) {
  531. if(rules && rules.length>0){
  532. this.rules=this.rules.filter(item=>{return item.from!=from});
  533. rules.forEach(item=>{
  534. let rule=this.formatRule(item, type, from);
  535. if(rule){
  536. this.rules.unshift(rule);
  537. }
  538. });
  539. }
  540. }
  541.  
  542. getRule(callback) {
  543. if(this.curSiteRule && this.curSiteRule.url){
  544. return this.curSiteRule;
  545. }
  546. var self=this;
  547.  
  548. function setRule(r){
  549. self.curSiteRule=r;
  550. debug(r);
  551. callback();
  552. }
  553.  
  554. function ruleMatch(r){
  555. let pageElement,nextLink,insert;
  556. if(r.pageElement)pageElement=r.type==0?getElementByXpath(r.pageElement):document.querySelector(r.pageElement);
  557. if(r.nextLink)nextLink=r.type==0?getElementByXpath(r.nextLink):document.querySelector(r.nextLink);
  558. if(r.insert)insert=r.type==0?getElementByXpath(r.insert):document.querySelector(r.insert);
  559. return !((r.pageElement && !pageElement) ||
  560. (r.nextLink && !nextLink) ||
  561. (r.insert && !insert));
  562. }
  563.  
  564. function checkRule(r){
  565. let urlReg=new RegExp(r.url, "i");
  566. if(urlReg.test(location.href)){
  567. if(r.wait){
  568. let waitTime=500,checkEval;
  569. if(isNaN(r.wait)){
  570. try{
  571. checkEval=Function("doc",'"use strict";' + r.wait);
  572. }catch(e){
  573. debug(e);
  574. }
  575. }else{
  576. waitTime=r.wait;
  577. }
  578. let checkReady=()=>{
  579. setTimeout(()=>{
  580. if(!ruleMatch(r) || (checkEval && !checkEval(document))){
  581. checkReady();
  582. }else{
  583. setRule(r);
  584. }
  585. },parseInt(waitTime));
  586. };
  587. checkReady();
  588. return true;
  589. }
  590. if(r.pinUrl){
  591. setRule(r);
  592. return true;
  593. }
  594. if(!ruleMatch(r)){
  595. return false;
  596. }
  597. setRule(r);
  598. return true;
  599. }
  600. return false;
  601. }
  602.  
  603. for(let i in this.hpRules){
  604. let rule=this.hpRules[i];
  605. if(!rule || !rule.url)continue;
  606. if(rule.singleUrl){
  607. if(location.origin+location.pathname==rule.url){
  608. setRule(rule);
  609. return;
  610. }
  611. continue;
  612. }
  613. if(checkRule(rule))return;
  614. }
  615. for(let i in this.customRules){
  616. let rule=this.customRules[i];
  617. if(!rule || !rule.url)continue;
  618. if(checkRule(rule))return;
  619. }
  620. let r=0;
  621. function searchByTime(){
  622. setTimeout(()=>{
  623. let end=r+80;
  624. end=end>self.rules.length?self.rules.length:end;
  625. for(;r<end;r++){
  626. let rule=self.rules[r];
  627. if(checkRule(rule))return;
  628. }
  629. if(end>=self.rules.length){
  630. self.curSiteRule={};
  631. self.curSiteRule.url=location.origin+location.pathname;
  632. self.curSiteRule.singleUrl=true;
  633. callback();
  634. return;
  635. }else{
  636. searchByTime();
  637. }
  638. },20);
  639. }
  640. searchByTime();
  641. }
  642.  
  643. geneSelector(ele){
  644. let selector=ele.tagName;
  645. //Google id class都是隨機。百度更過分,style script順序都是隨機的
  646. //if(ele.id) selector += '#' + ele.id;
  647. //if(ele.classList) selector += [].map.call(ele.classList,d=>'.'+d).join('');
  648. let parent = ele.parentElement;
  649. if(parent){
  650. let i,j=0;
  651. for(i=0;i<parent.children.length;i++){
  652. if(parent.children[i].tagName==selector){
  653. j++;
  654. if(parent.children[i]==ele){
  655. break;
  656. }
  657. }
  658. }
  659. selector = this.geneSelector(parent) + ' > ' + selector + (parent.tagName=="HTML"?"":`:nth-of-type(${j})`);
  660. }
  661. return selector;
  662. }
  663.  
  664. getPageElement(doc, curWin, dontFind) {
  665. let pageElement=null;
  666. let self=this;
  667. if(this.curSiteRule.pageElement){
  668. pageElement=this.curSiteRule.type==0?getAllElementsByXpath(this.curSiteRule.pageElement,doc,doc):doc.querySelectorAll(this.curSiteRule.pageElement);
  669. }
  670. if((!pageElement || pageElement.length==0) && curWin && !dontFind){
  671. let body=doc.body;
  672. if(!body)return null;
  673. let bodyHeight=parseInt(body.scrollHeight);
  674. let curHeight=bodyHeight;
  675. function checkElement(ele){
  676. if(curHeight/bodyHeight<=0.30){
  677. self.curSiteRule.pageElement=allOfBody;
  678. debug(self.curSiteRule.pageElement);
  679. return [body];
  680. }
  681. if(ele.tagName=="TBODY" || ele.tagName=="UL"){
  682. self.curSiteRule.pageElement=self.geneSelector(ele)+">*";
  683. if(ele.children.length>0 && ele.children[0].querySelector("th")){
  684. self.curSiteRule.pageElement+=":not(:first-child)";
  685. }
  686. debug(self.curSiteRule.pageElement);
  687. return ele.children;
  688. }
  689. if(ele.children.length==0 && !self.curSiteRule.pageElement){
  690. if(ele.parentNode.tagName=="P")ele=ele.parentNode;
  691. self.curSiteRule.pageElement=self.geneSelector(ele.parentNode)+">"+ele.tagName;
  692. debug(self.curSiteRule.pageElement);
  693. return [ele];
  694. }
  695. let i,maxHeight=curHeight*0.6,curMaxEle=null,curMaxArea=0,maxWidth=0;
  696. let isHori=true;
  697. let offsetTop=ele.children[0].offsetTop;
  698. for(i=0;i<ele.children.length;i++){
  699. if(ele.children[i].offsetTop!=offsetTop){
  700. isHori=false;
  701. break;
  702. }
  703. }
  704. for(i=0;i<ele.children.length;i++){
  705. let curNode=ele.children[i];
  706. if(curNode.tagName=="CANVAS")continue;
  707. if(curNode.tagName!="IMG" && curNode.innerHTML=="")continue;
  708. let comStyle=curWin.getComputedStyle(curNode);
  709. let h=parseInt(curNode.scrollHeight);
  710. let w=parseInt(curNode.scrollWidth);
  711. if(isNaN(h) || isNaN(w))continue;
  712. if(isHori && h==0)continue;
  713. let a=h*w+h,moreChild=curNode.children[0];
  714. while(moreChild){
  715. comStyle=curWin.getComputedStyle(moreChild);
  716. let ch=parseInt(moreChild.scrollHeight);
  717. let cw=parseInt(moreChild.scrollWidth);
  718. if(h<ch)h=ch;
  719. if(moreChild.innerText!="" && !isNaN(ch) && !isNaN(cw)){
  720. a+=ch*cw;
  721. }
  722. moreChild=moreChild.nextElementSibling;
  723. }
  724. let isMax=false;
  725. if(isHori){
  726. if(maxWidth<w){
  727. isMax=true;
  728. }else if(maxWidth==w && curMaxArea<a){
  729. isMax=true;
  730. }
  731. }else{
  732. isMax=curMaxArea<a;
  733. }
  734. if(curMaxEle==null || isMax){
  735. if(h>0)curHeight=h;
  736. curMaxArea=a;
  737. maxWidth=w;
  738. curMaxEle=curNode;
  739. }
  740. }
  741. if(curMaxEle && (isHori || curHeight>maxHeight)){
  742. return checkElement(curMaxEle);
  743. }
  744. if(!self.curSiteRule.pageElement){
  745. if(ele.tagName=="P" || ele.tagName=="BR")ele=ele.parentNode;
  746. self.curSiteRule.pageElement=self.geneSelector(ele);
  747. if(ele.children.length>1 && ele.tagName!="UL")self.curSiteRule.pageElement+=">*";
  748. debug(self.curSiteRule.pageElement);
  749. }
  750. return (ele.tagName=="UL"||ele.children.length==1)?[ele]:ele.children;
  751. }
  752. pageElement=checkElement(body);
  753. if(pageElement)this.saveCurSiteRule();
  754. }
  755. /*if(this.insert && this.insert.parentNode && pageElement && pageElement[0]){
  756. let example=this.insertPos==2?this.insert.children[0]:this.insert;
  757. let inTable=example.parentNode.tagName=="TABLE" ||
  758. example.tagName=="TR" ||
  759. example.tagName=="TBODY" ||
  760. (example.previousElementSibling && example.previousElementSibling.tagName=="TR") ||
  761. (example.previousElementSibling && example.previousElementSibling.tagName=="TBODY");
  762. if(inTable && pageElement[0].tagName!="TR" && pageElement[0].tagName!="TBODY"){
  763. pageElement=null;
  764. }
  765. }*/
  766. return pageElement;
  767. }
  768.  
  769. getPage(doc){
  770. if(_unsafeWindow.Discourse)return {};
  771. let canSave=false;//發現頁碼選擇器在其他頁對不上,還是別保存了
  772. let url=this.curUrl.replace("#!","").replace("index.php?","?");
  773. let pageNum=1,preStr="",afterStr="";
  774. let pageMatch1=url.match(/(.*[a-z\/\-_](?:p|page)?\/?)(\d+)(\.s?html?$|\/?$)/i);
  775. let pageMatch2=url.match(/(.*[\?&]p(?:age)?=)(\d+)($|[#&].*)/i);
  776. if(pageMatch1){
  777. preStr=pageMatch1[1];
  778. pageNum=parseInt(pageMatch1[2]);
  779. afterStr=pageMatch1[3];
  780. }else if(pageMatch2){
  781. preStr=pageMatch2[1];
  782. pageNum=parseInt(pageMatch2[2]);
  783. afterStr=pageMatch2[3];
  784. }
  785. let curPage=doc,i,cur,jsNext;
  786. let next=curPage.querySelector(".page-next>a")||
  787. curPage.querySelector("a.next_page")||
  788. curPage.querySelector("#next_page")||
  789. curPage.querySelector(".nextPage")||
  790. curPage.querySelector("a[data-pagination=next]")||
  791. curPage.querySelector(".pagination a[rel=next]")||
  792. curPage.querySelector(".pagination-nav__item--next>a")||
  793. curPage.querySelector("a.pageright")||
  794. curPage.querySelector("a#rightFix")||
  795. curPage.querySelector("a.next")||
  796. curPage.querySelector("a#next")||
  797. curPage.querySelector(".next>a")||
  798. curPage.querySelector(".next>button")||
  799. curPage.querySelector("a[alt=next]")||
  800. curPage.querySelector("[title=next]");
  801. if(next && (!next.href || /^javascript:/.test(next.href))){
  802. jsNext=next;
  803. next=null;
  804. }
  805. if(!next){
  806. next=curPage.querySelectorAll("[aria-label='Next']");
  807. if(next && next.length==1){
  808. next=next[0];
  809. if(!next.href || /^javascript:/.test(next.href)){
  810. jsNext=next;
  811. next=null;
  812. }
  813. }else{
  814. next=null;
  815. }
  816. }
  817. if(!next){
  818. next=curPage.querySelectorAll("[aria-label='Next page']");
  819. if(next && next.length==1){
  820. next=next[0];
  821. if(!next.href || /^javascript:/.test(next.href)){
  822. jsNext=next;
  823. next=null;
  824. }
  825. }else{
  826. next=null;
  827. }
  828. }
  829. if(!next){
  830. let pageDiv=curPage.querySelector("div.wp-pagenavi");
  831. if(pageDiv){
  832. cur=pageDiv.querySelector("span.current");
  833. if(cur){
  834. next=cur.nextSibling;
  835. }
  836. }else{
  837. cur=curPage.querySelector("div.article-paging>span");
  838. if(cur){
  839. next=cur.nextElementSibling;
  840. }
  841. }
  842. }
  843. if(!next){
  844. let pageDiv=curPage.querySelector("div.pages>ul");
  845. if(pageDiv){
  846. cur=pageDiv.querySelector("li>b");
  847. if(cur)next=cur.parentNode.nextElementSibling.querySelector("a");
  848. }
  849. }
  850. if(!next){
  851. let aTags=curPage.querySelectorAll("a");
  852. let next1,next2,next3,next4,nextJs1,nextJs2,nextJs3;
  853. for(i=aTags.length-1;i>=0;i--){
  854. let aTag=aTags[i];
  855. if(aTag.innerText=="§")continue;
  856. if(aTag.style.display=="none")continue;
  857. if(next1 && next2 && next3 && next4)break;
  858. if(!next1){
  859. if(/^\s*[下后後][一1]?[页頁张張]|^next( page)?\s*›?$|次のページ/i.test(aTag.innerText)){
  860. if(aTag.innerText.length>15)continue;
  861. if(!aTag.href || /^javascript:/.test(aTag.href)){
  862. if(!nextJs1)nextJs1=aTag;
  863. }else{
  864. next1=aTag;
  865. }
  866. }
  867. }
  868. if(!next2){
  869. if(/^\s*[下后後][一1]?[章话話]/i.test(aTag.innerText)){
  870. if(!aTag.href || /^javascript:/.test(aTag.href)){
  871. if(!nextJs2)nextJs2=aTag;
  872. }else{
  873. next2=aTag;
  874. }
  875. }
  876. }
  877. if(!next3){
  878. if(aTag.innerText=="&gt;" || aTag.innerText=="▶" || aTag.innerText==">" || aTag.innerText=="›" || /nextpage/i.test(aTag.className)){
  879. if(!aTag.href || /^javascript:/.test(aTag.href)){
  880. if(!nextJs3)nextJs3=aTag;
  881. }else{
  882. next3=aTag;
  883. }
  884. }
  885. }
  886. if(!aTag.href || /^javascript:/.test(aTag.href))continue;
  887. if(!next4){
  888. if(pageNum<999 && aTag.href.replace("?&","?").replace("#!","").replace("index.php?","?").replace(preStr,"").replace(afterStr,"")==pageNum+1){
  889. next4=aTag;
  890. }else if(this.curUrl!=aTag.href && aTag.href.replace("?&","?").replace("index.php?","?").indexOf(url)!=-1 && /^[\/\?&]?[_-]?(p|page)?=?\/?2(\/|\?|&|$)/i.test(aTag.href.replace(url,"").replace(/\.s?html?$/i,""))){
  891. let curHref=aTag.getAttribute("href");
  892. let pageOne=curHref.replace(/\/2(\/|\?|&|$)/,"/1$1");
  893. if(pageOne==curHref)pageOne=null;
  894. else pageOne=curPage.querySelector(`a[href='${pageOne}']`);
  895. if(!pageOne)next4=aTag;
  896. }
  897. }
  898. }
  899. next=next1||next3||next4||next2||nextJs1||nextJs3||nextJs2;
  900. }
  901. if(!next)next=jsNext;
  902. if(next && next.classList.contains("results-more"))next=null;
  903. return {next:next,canSave:canSave};
  904. }
  905.  
  906. canonicalUri(src, base_path) {
  907. if(src.charAt(0)=="#")return location.href+src;
  908. var root_page = /^[^?#]*\//.exec(location.href)[0],
  909. root_domain = /^\w+\:\/\/\/?[^\/]+/.exec(root_page)[0],
  910. absolute_regex = /^\w+\:\/\//;
  911. src=src.replace(/\.\//,"");
  912. if (/^\/\/\/?/.test(src)){
  913. src = location.protocol + src;
  914. }
  915. else if (!absolute_regex.test(src) && src.charAt(0) != "/"){
  916. src = (base_path || "") + src;
  917. }
  918. return (absolute_regex.test(src) ? src : ((src.charAt(0) == "/" ? root_domain : root_page) + src));
  919. }
  920.  
  921. getLinkByPage(url, pageNum) {
  922. if(!url)return;
  923. if(this.curSiteRule.pageNum){
  924. let result=this.curSiteRule.pageNum;
  925. let strMatch=result.match(/\{.*?}/);
  926. if(!strMatch)return null;
  927. let urlReg=new RegExp("("+result.replace(strMatch[0], ")\\d+(")+")");
  928. let code=strMatch[0].replace(/^{/,"").replace(/}$/,"").replace(/\$p/g,pageNum);
  929. if(code==pageNum){
  930. result=url.replace(urlReg,"$1"+code+"$2");
  931. }else{
  932. try{
  933. code=Function('"use strict";return ' + code)();
  934. result=url.replace(urlReg,"$1"+code+"$2");
  935. }catch(e){
  936. debug(e);
  937. }
  938. }
  939. return result==url?url.replace(/([&\/\?](p=|page[=\/]))\d+/i, "$1"+pageNum):result;
  940. }else{
  941. return url.replace(/([&\/\?](p=|page[=\/]))\d+/i, "$1"+pageNum);
  942. }
  943. }
  944.  
  945. getNextLink(doc) {
  946. let nextLink=null,page;
  947. if(this.curSiteRule.pageElementByJs){
  948. this.nextLinkHref="#";
  949. return true;
  950. }else if(this.curSiteRule.nextLinkByJs){
  951. try{
  952. let targetUrl=Function("doc",'"use strict";' + this.curSiteRule.nextLinkByJs)(doc);
  953. if(targetUrl)nextLink={href:targetUrl};
  954. }catch(e){
  955. debug(e);
  956. }
  957. }else if(this.curSiteRule.nextLinkByUrl){
  958. let targetUrl=this.curUrl.replace(new RegExp(this.curSiteRule.nextLinkByUrl[0]), this.curSiteRule.nextLinkByUrl[1]);
  959. if(targetUrl != this.curUrl){
  960. let reps=targetUrl.match(/{.*?}/g);
  961. if(reps){
  962. reps.forEach(rep=>{
  963. let code=rep.replace("{","").replace("}","");
  964. let result=code.match(/^(\d+)\+1$/);
  965. if(result){
  966. result=parseInt(result[1])+1;
  967. }else{
  968. try{
  969. result=Function('"use strict";return ' + code)();
  970. }catch(e){
  971. debug(e);
  972. }
  973. }
  974. targetUrl=targetUrl.replace(rep, result);
  975. });
  976. }
  977. }
  978. nextLink={href:targetUrl};
  979. }else if(this.curSiteRule.nextLink){
  980. if(this.curSiteRule.nextLink!="0"){
  981. nextLink=this.curSiteRule.type==0?getElementByXpath(this.curSiteRule.nextLink,doc,doc):doc.querySelector(this.curSiteRule.nextLink);
  982. }
  983. }else{
  984. page=this.getPage(doc);
  985. nextLink=page.next;
  986. if(nextLink){
  987. if(nextLink.tagName=="INPUT" && nextLink.parentNode.tagName=="FORM"){
  988. let params=[];
  989. let form=nextLink.parentNode;
  990. [].forEach.call(form.querySelectorAll("input"), input=>{
  991. params.push(input.name+'='+input.value);
  992. });
  993. nextLink.href=form.action+'?'+params.join('&');
  994. }
  995. if(nextLink.classList.contains("noClick")){
  996. this.nextLinkHref=false;
  997. return null;
  998. }else if(doc==document){
  999. if((!nextLink.href || /^javascript:/.test(nextLink.href)) && !isVisible(nextLink, _unsafeWindow)){
  1000. this.nextLinkHref=false;
  1001. return null;
  1002. }else{
  1003. let nextLinkCs=_unsafeWindow.getComputedStyle(nextLink);
  1004. if(nextLinkCs.cursor=="not-allowed"){
  1005. this.nextLinkHref=false;
  1006. return null;
  1007. }
  1008. }
  1009. }
  1010. }
  1011. }
  1012. if(nextLink){
  1013. if(nextLink.href && nextLink.href==this.curUrl){
  1014. nextLink=null;
  1015. }else if(/^javascript:/.test(nextLink.href) && (this.curSiteRule.action==0 || this.curSiteRule.action==1)){
  1016. nextLink=null;
  1017. }
  1018. /*if(!this.curSiteRule.nextLink && page && page.canSave){
  1019. this.curSiteRule.nextLink=this.geneSelector(nextLink);
  1020. this.curSiteRule.type=1;
  1021. this.saveCurSiteRule();
  1022. }*/
  1023. }
  1024. if(nextLink){
  1025. this.nextLinkHref=(nextLink.href && !/^javascript:/.test(nextLink.href))?this.canonicalUri(nextLink.href):"#";
  1026. debug(nextLink);
  1027. }else{
  1028. this.nextLinkHref=false;
  1029. }
  1030. return nextLink;
  1031. }
  1032.  
  1033. getInsert(refresh) {
  1034. if(refresh){
  1035. this.insert=null;
  1036. }
  1037. if(this.insert && !refresh){
  1038. let parent=this.insert;
  1039. while(parent && parent.nodeName!="BODY"){
  1040. parent=parent.parentNode;
  1041. }
  1042. if(parent && parent.nodeName=="BODY"){
  1043. return this.insert;
  1044. }
  1045. }
  1046. if(this.curSiteRule.insert){
  1047. this.insert=this.curSiteRule.type==0?getElementByXpath(this.curSiteRule.insert,document):document.querySelector(this.curSiteRule.insert);
  1048. }else{
  1049. let pageElement=this.getPageElement(document, _unsafeWindow);
  1050. if(pageElement && pageElement.length>0){
  1051. var pELast = pageElement[pageElement.length - 1];
  1052. this.insert = pELast.nextSibling ? pELast.nextSibling : pELast.parentNode.appendChild(document.createTextNode(' '));
  1053. }
  1054. }
  1055. return this.insert;
  1056. }
  1057.  
  1058. pageInit(doc,eles){
  1059. let code=this.curSiteRule.pageInit;
  1060. if(code){
  1061. try{
  1062. Function("doc","eles",'"use strict";' + code)(doc,eles);
  1063. }catch(e){
  1064. debug(e);
  1065. }
  1066. }
  1067. }
  1068.  
  1069. pageAction(doc,eles){
  1070. let code=this.curSiteRule.pageAction;
  1071. if(code){
  1072. try{
  1073. Function("doc","eles",'"use strict";' + code)(doc,eles);
  1074. }catch(e){
  1075. debug(e);
  1076. }
  1077. }
  1078. let setLazyImg=img=>{
  1079. let realSrc;
  1080. if(img.getAttribute("_src") && !img.src){
  1081. realSrc=img.getAttribute("_src");
  1082. }else if(img.dataset && img.dataset.original){
  1083. realSrc=img.dataset.original;
  1084. }else if(img.dataset && img.dataset.src){
  1085. realSrc=img.dataset.src;
  1086. }else if(img._lazyrias && img._lazyrias.srcset){
  1087. realSrc=img._lazyrias.srcset[img._lazyrias.srcset.length-1];
  1088. }else if(img.dataset && img.dataset.origFile){
  1089. realSrc=img.dataset.origFile;
  1090. }else if(img.srcset){
  1091. var srcs=img.srcset.split(","),largeSize=0;
  1092. srcs.forEach(srci=>{
  1093. let srcInfo=srci.trim().split(" "),curSize=parseInt(srcInfo[1]);
  1094. if(srcInfo[1] && curSize>largeSize){
  1095. largeSize=curSize;
  1096. realSrc=srcInfo[0];
  1097. }
  1098. });
  1099. }
  1100. if(realSrc){
  1101. img.src=realSrc;
  1102. img.style.display="block";
  1103. }
  1104. };
  1105. [].forEach.call(eles, ele=>{
  1106. if(ele.tagName=="IMG"){
  1107. setLazyImg(ele);
  1108. }else{
  1109. [].forEach.call(ele.querySelectorAll("img"), img=>{
  1110. setLazyImg(img);
  1111. });
  1112. }
  1113. if(ele.tagName=="A" && ele.classList.contains("lazyload")){
  1114. if(ele.dataset.original){
  1115. ele.style.backgroundImage='url("'+ele.dataset.original+'")';
  1116. }
  1117. }else{
  1118. [].forEach.call(ele.querySelectorAll("a.lazyload"), a=>{
  1119. if(a.dataset.original){
  1120. a.style.backgroundImage='url("'+a.dataset.original+'")';
  1121. }
  1122. });
  1123. }
  1124. });
  1125. let lazyImgSrc=this.curSiteRule.lazyImgSrc;
  1126. if(lazyImgSrc){
  1127. [].forEach.call(eles, ele=>{
  1128. [].forEach.call(ele.querySelectorAll("img"), img=>{
  1129. if(img.getAttribute(lazyImgSrc)){
  1130. img.src=img.getAttribute(lazyImgSrc);
  1131. }
  1132. });
  1133. });
  1134. }
  1135. }
  1136.  
  1137. initPage(callback){
  1138. let self=this;
  1139. curPage=1;
  1140. //if(this.curSiteRule.url && !this.curSiteRule.singleUrl)return;
  1141. this.curSiteRule={};
  1142. this.pageDoc=document;
  1143. this.nextLinkHref=null;
  1144. this.curUrl=location.href;
  1145. this.getRule(()=>{
  1146. if(self.curSiteRule.enable==0){
  1147. debug("Stop as rule disable");
  1148. isPause=true;
  1149. return;
  1150. }
  1151. if(self.curSiteRule && !self.curSiteRule.singleUrl){
  1152. self.hpRules=self.hpRules.filter(item=>{return item&&item.url!=self.curSiteRule.url});
  1153. self.hpRules.unshift(self.curSiteRule);
  1154. if(self.hpRules.length>30){
  1155. self.hpRules.pop();
  1156. }
  1157. storage.setItem("hpRules", self.hpRules);
  1158. }
  1159. let css=self.curSiteRule.css;
  1160. if(css){
  1161. _GM_addStyle(css);
  1162. }
  1163. let code=self.curSiteRule.init;
  1164. if(code){
  1165. try{
  1166. Function('doc','"use strict";' + code)(null);
  1167. }catch(e){
  1168. debug(e);
  1169. }
  1170. }
  1171. self.getNextLink(document);
  1172. callback();
  1173. });
  1174. }
  1175.  
  1176. insertPage(doc, eles, url, callback, tried){
  1177. let oldUrl=this.curUrl;
  1178. let oldTitle=this.pageDoc.title;
  1179. this.pageDoc=doc;
  1180. this.curUrl=url;
  1181. let nextLink=this.getNextLink(doc);
  1182. if(curPage==1 && !tried && !this.nextLinkHref && this.curSiteRule.singleUrl && this.curSiteRule.pageElement && this.curSiteRule.pageElement!=allOfBody){
  1183. this.curSiteRule.action=1;
  1184. this.curUrl=location.href;
  1185. return false;
  1186. }
  1187. if(callback)callback(eles);
  1188. this.getInsert();
  1189. var self=this,newEles=[];
  1190. if(!eles || eles.length==0 || !self.insert || !self.insert.parentNode){
  1191. }else{
  1192. this.pageInit(doc, eles);
  1193. [].forEach.call(eles, ele=>{
  1194. let newEle=ele.cloneNode(true);
  1195. let oldCanvass=ele.querySelectorAll("canvas");
  1196. let newCanvass=newEle.querySelectorAll("canvas");
  1197. for(let i=0;i<oldCanvass.length;i++){
  1198. let oldCanvas=oldCanvass[i];
  1199. let newCanvas=newCanvass[i];
  1200. newCanvas.getContext('2d').drawImage(oldCanvas, 0, 0);
  1201. }
  1202. if(self.curSiteRule.insertPos==2){
  1203. self.insert.appendChild(newEle);
  1204. }else{
  1205. self.insert.parentNode.insertBefore(newEle, self.insert);
  1206. }
  1207. newEles.push(newEle);
  1208. });
  1209. }
  1210. this.pageAction(doc, newEles);
  1211. if(oldUrl!=location.href){
  1212. let isJs=/^(javascript|#)/.test(oldUrl.replace(location.href,""));
  1213. if(rulesData.enableHistory && !isJs){
  1214. _unsafeWindow.history.replaceState(undefined, oldTitle, oldUrl);
  1215. document.title=oldTitle;
  1216. }
  1217. }
  1218. return true;
  1219. }
  1220. }
  1221. var ruleParser = new RuleParser();
  1222.  
  1223. function initConfig(){
  1224. _GM_registerMenuCommand(i18n(forceState==1?"enable":"disableSite"), ()=>{
  1225. storage.setItem("forceState_"+location.host, (forceState==1?0:1));
  1226. location.reload();
  1227. });
  1228. _GM_registerMenuCommand(i18n("update"), ()=>{
  1229. updateRules(()=>{
  1230. alert(i18n("updateSucc"));
  1231. location.reload();
  1232. },(rule,err)=>{
  1233. alert("Update "+rule.url+" rules fail!");
  1234. });
  1235. alert(i18n("beginUpdate"));
  1236. });
  1237.  
  1238. var configCon,insertPos;
  1239. if(location.href==configPage){
  1240. _GM_addStyle(`
  1241. p>span:nth-child(1),p>span:nth-child(2),p>span:nth-child(3){
  1242. cursor: pointer;
  1243. user-select: none;
  1244. }
  1245. p>span:nth-child(1):hover,p>span:nth-child(2):hover,p>span:nth-child(3):hover{
  1246. color:red;
  1247. }
  1248. .updateDate{
  1249. cursor: pointer;
  1250. user-select: none;
  1251. }
  1252. .updateDate:hover{
  1253. color:red;
  1254. }
  1255. `);
  1256. configCon=document.querySelector(".markdown-body");
  1257. insertPos=configCon.querySelector("hr");
  1258. }else if(location.href==configPage){//2nd todo
  1259. }else return false;
  1260. class Rulebar {
  1261. init(ruleUrl){
  1262. this.ruleUrl=ruleUrl;
  1263. this.item=document.createElement("p");
  1264. this.item.title=ruleUrl.type==0?"AutoPagerize Rules":"Pagetual Rules";
  1265. this.item.dataset.id=this.ruleUrl.id;
  1266. let url=document.createElement("span");
  1267. url.innerHTML=ruleUrl.url;
  1268. let up=document.createElement("span");
  1269. up.innerHTML="↑ ";
  1270. up.title=i18n("sortTitle");
  1271. let down=document.createElement("span");
  1272. down.innerHTML="↓ ";
  1273. down.title=i18n("sortTitle");
  1274. let del=document.createElement("span");
  1275. del.innerHTML="× ";
  1276. up.onclick=e=>{
  1277. this.moveUp();
  1278. };
  1279. down.onclick=e=>{
  1280. this.moveDown();
  1281. };
  1282. del.onclick=e=>{
  1283. this.del();
  1284. };
  1285. this.item.appendChild(up);
  1286. this.item.appendChild(down);
  1287. this.item.appendChild(del);
  1288. this.item.appendChild(url);
  1289. configCon.insertBefore(this.item, insertPos);
  1290. }
  1291. saveSort(){
  1292. let sort=[];
  1293. [].forEach.call(this.item.parentNode.querySelectorAll("p[data-id]"), i=>{
  1294. sort.push(i.dataset.id);
  1295. });
  1296. rulesData.sort=sort;
  1297. storage.setItem("rulesData", rulesData);
  1298. }
  1299. moveUp(){
  1300. let preE=this.item.previousElementSibling;
  1301. if(preE.tagName=="P" && preE.children.length>1){
  1302. this.item.parentNode.insertBefore(this.item,preE);
  1303. this.saveSort();
  1304. }
  1305. }
  1306. moveDown(){
  1307. let nextE=this.item.nextElementSibling;
  1308. if(nextE.tagName=="P" && nextE.children.length>1){
  1309. this.item.parentNode.insertBefore(nextE,this.item);
  1310. this.saveSort();
  1311. }
  1312. }
  1313. del(){
  1314. if(this.ruleUrl.id<2){
  1315. alert(i18n("cantDel"));
  1316. }else if(window.confirm(i18n("confirmDel"))){
  1317. for(let u=0;u<rulesData.urls.length;u++){
  1318. if(this.ruleUrl.id==rulesData.urls[u].id){
  1319. rulesData.urls.splice(u,1);
  1320. break;
  1321. }
  1322. }
  1323. for(let u=0;u<rulesData.sort.length;u++){
  1324. if(this.ruleUrl.id==rulesData.sort[u]){
  1325. rulesData.sort.splice(u,1);
  1326. break;
  1327. }
  1328. }
  1329. storage.setItem("rulesData", rulesData);
  1330. ruleParser.rules=ruleParser.rules.filter(item=>{return item.from!=this.ruleUrl.id});
  1331. storage.setItem("rules", ruleParser.rules);
  1332. this.item.parentNode.removeChild(this.item);
  1333. //location.reload();
  1334. }
  1335. }
  1336. }
  1337. let updateP=document.createElement("p"),i=0;
  1338. let now=new Date().getTime(),inUpdate=false;
  1339.  
  1340.  
  1341. let pastDate=(new Date(updateDate)).toString(),passStr;
  1342. let passTime=(now-updateDate)/1000;
  1343. if(isNaN(passTime)){
  1344. passStr=i18n("firstUpdate");
  1345. }else if(passTime<60){
  1346. passStr=i18n("passSec", parseInt(passTime))+" ← "+i18n("click2update");
  1347. }else if(passTime<60*60){
  1348. passStr=i18n("passMin", parseInt(passTime/60))+" ← "+i18n("click2update");
  1349. }else if(passTime<60*60*24){
  1350. passStr=i18n("passHour", parseInt(passTime/3600))+" ← "+i18n("click2update");
  1351. }else{
  1352. passStr=i18n("passDay", parseInt(passTime/86400))+" ← "+i18n("click2update");
  1353. }
  1354.  
  1355.  
  1356. updateP.className="updateDate";
  1357. updateP.innerHTML=passStr;
  1358. updateP.title=i18n("update")+" - "+pastDate;
  1359. updateP.onclick=e=>{
  1360. updateRules(()=>{
  1361. alert(i18n("updateSucc"));
  1362. updateP.innerHTML=i18n("passSec", 0);
  1363. updateP.title=i18n("update");
  1364. },(rule,err)=>{
  1365. alert("Update "+rule.url+" rules fail!");
  1366. });
  1367. alert(i18n("beginUpdate"));
  1368. };
  1369. configCon.insertBefore(updateP, insertPos);
  1370. if(ruleUrls){
  1371. ruleUrls.forEach(ruleUrl=>{
  1372. var rulebar=new Rulebar();
  1373. rulebar.init(ruleUrl);
  1374. });
  1375. }
  1376. let customUrlsTitle=document.createElement("h2");
  1377. customUrlsTitle.innerHTML=i18n("customUrls");
  1378. configCon.insertBefore(customUrlsTitle, insertPos);
  1379. let customUrlsInput=document.createElement("textarea");
  1380. customUrlsInput.style.width="100%";
  1381. customUrlsInput.placeholder="0|http://wedata.net/databases/AutoPagerize/items_all.json";
  1382. configCon.insertBefore(customUrlsInput, insertPos);
  1383.  
  1384. let opacityTitle=document.createElement("h2");
  1385. opacityTitle.innerHTML=i18n("opacity");
  1386. let opacityInput=document.createElement("input");
  1387. opacityInput.value=rulesData.opacity*100;
  1388. opacityInput.type="number";
  1389. opacityInput.style.width="50px";
  1390. opacityInput.style.margin="0 0 0 10px";
  1391. opacityTitle.appendChild(opacityInput);
  1392. configCon.insertBefore(opacityTitle, insertPos);
  1393.  
  1394. function createCheckbox(innerText, val){
  1395. let title=document.createElement("h2");
  1396. title.innerHTML=innerText;
  1397. let input=document.createElement("input");
  1398. input.type="checkbox";
  1399. input.style.width="50px";
  1400. input.style.height="20px";
  1401. input.checked=val;
  1402. title.appendChild(input);
  1403. configCon.insertBefore(title, insertPos);
  1404. return input;
  1405. }
  1406.  
  1407. let hideBarInput=createCheckbox(i18n("hideBar"), rulesData.hideBar);
  1408. let dbClick2StopInput=createCheckbox(i18n("dbClick2Stop"), rulesData.dbClick2Stop);
  1409. let enableWhiteListInput=createCheckbox(i18n("autoRun"), rulesData.enableWhiteList!=true);
  1410. let enableDebugInput=createCheckbox(i18n("enableDebug"), rulesData.enableDebug!=false);
  1411. let enableHistoryInput=createCheckbox(i18n("enableHistory"), rulesData.enableHistory!=false);
  1412. let initRunInput=createCheckbox(i18n("initRun"), rulesData.initRun!=false);
  1413.  
  1414. let customRulesTitle=document.createElement("h2");
  1415. customRulesTitle.innerHTML=i18n("customRules")
  1416. configCon.insertBefore(customRulesTitle, insertPos);
  1417. let customRulesInput=document.createElement("textarea");
  1418. customRulesInput.style.width="100%";
  1419. customRulesInput.style.height="500px";
  1420. customRulesInput.placeholder=`[\n {\n "name":"yande",\n "action":"0",\n "url":"^https:\/\/yande\\.re\/",\n "pageElement":"ul#post-list-posts>li",\n "nextLink":"a.next_page",\n "css":".javascript-hide {display: inline-block !important;}"\n },\n {\n "name":"tieba",\n "action":"1",\n "url":"^https:\/\/tieba\\.baidu.com\/f\\?kw=",\n "pageElement":"ul#thread_list>li",\n "nextLink":".next.pagination-item "\n }\n]`;
  1421. customRulesInput.value=getFormatJSON(ruleParser.customRules);
  1422. configCon.insertBefore(customRulesInput, insertPos);
  1423. let saveBtn=document.createElement("button");
  1424. saveBtn.innerHTML=i18n("save");
  1425. saveBtn.style.width="100%";
  1426. configCon.insertBefore(saveBtn, insertPos);
  1427. saveBtn.onclick=e=>{
  1428. try{
  1429. storage.setItem("hpRules", []);
  1430. if(customRulesInput.value==""){
  1431. storage.setItem("customRules", "");
  1432. }else{
  1433. let customRules=JSON.parse(customRulesInput.value);
  1434. if(Array && Array.isArray && !Array.isArray(customRules)){
  1435. alert("Rules must be a Array!");
  1436. return;
  1437. }
  1438. debug(customRules);
  1439. storage.setItem("customRules", customRules);
  1440. }
  1441. }catch(e){
  1442. debug(e);
  1443. alert("JSON error, check again!");
  1444. return;
  1445. }
  1446. rulesData.opacity=opacityInput.value/100;
  1447. rulesData.hideBar=hideBarInput.checked;
  1448. rulesData.dbClick2Stop=dbClick2StopInput.checked;
  1449. rulesData.enableWhiteList=!enableWhiteListInput.checked;
  1450. rulesData.enableDebug=enableDebugInput.checked;
  1451. rulesData.enableHistory=enableHistoryInput.checked;
  1452. rulesData.initRun=initRunInput.checked;
  1453. storage.setItem("rulesData", rulesData);
  1454. let customUrls=customUrlsInput.value.trim();
  1455. if(customUrls){
  1456. customUrls=customUrls.split(/\n/);
  1457. for(let c=0;c<customUrls.length;c++){
  1458. let urlArr=customUrls[c].split("|"),url,type=1;
  1459. if(urlArr.length==1){
  1460. url=urlArr[0].trim();
  1461. if(!/^http/.test(url)){
  1462. alert("Wrong url, check again!");
  1463. return;
  1464. }
  1465. }else if(urlArr.length==2){
  1466. type=urlArr[0].trim();
  1467. url=urlArr[1].trim();
  1468. if(!/^http/.test(url)){
  1469. alert("Wrong url, check again!");
  1470. return;
  1471. }
  1472. }else{
  1473. break;
  1474. }
  1475. let maxId=0,hasUrl=false;
  1476. if(!rulesData.urls){
  1477. rulesData.urls=[];
  1478. maxId=1;
  1479. }else{
  1480. rulesData.urls.forEach(u=>{
  1481. if(maxId<u.id){
  1482. maxId=u.id;
  1483. }
  1484. if(u.url==url){
  1485. hasUrl=true;
  1486. }
  1487. });
  1488. if(hasUrl)break;
  1489. }
  1490. rulesData.urls.push({id:maxId+1,url:url,type:type});
  1491. rulesData.sort.push(maxId+1);
  1492. storage.setItem("rulesData", rulesData);
  1493. }
  1494. }
  1495. alert("Modified successfully");
  1496. location.reload();
  1497. };
  1498. return true;
  1499. }
  1500.  
  1501. var inUpdate=false;
  1502. function updateRules(success,fail){
  1503. if(inUpdate)return;
  1504. inUpdate=true;
  1505. let ruleIndex=ruleUrls.length-1;
  1506. storage.setItem("hpRules", []);
  1507. function addNextRule(){
  1508. if(ruleIndex<0){
  1509. let now=new Date().getTime();
  1510. storage.setItem("ruleLastUpdate", now);
  1511. storage.setItem("rules", ruleParser.rules);
  1512. inUpdate=false;
  1513. success();
  1514. }else{
  1515. let rule=ruleUrls[ruleIndex--];
  1516. ruleParser.addRuleByUrl(rule.url, rule.type, rule.id, (json,err)=>{
  1517. if(!json){
  1518. fail(rule,err);
  1519. }
  1520. storage.setItem("rules", ruleParser.rules);
  1521. addNextRule();
  1522. })
  1523. }
  1524. }
  1525. addNextRule();
  1526. }
  1527.  
  1528. function objIsArr(obj) {
  1529. return obj &&
  1530. typeof obj === 'object' &&
  1531. typeof obj.length === 'number' &&
  1532. !(obj.propertyIsEnumerable('length'));
  1533. }
  1534.  
  1535. function isVisible(el, win) {
  1536. if(!el.offsetParent)return false;
  1537. var loopable = true,
  1538. visible = el.tagName && win.getComputedStyle(el).display != 'none' && win.getComputedStyle(el).visibility != 'hidden';
  1539. while(loopable && visible) {
  1540. el = el.parentNode;
  1541.  
  1542. if(el && el.tagName && el.tagName!="BODY") {
  1543. visible = win.getComputedStyle(el).display != 'none' && win.getComputedStyle(el).visibility != 'hidden';
  1544. }else {
  1545. loopable = false;
  1546. }
  1547. }
  1548. return visible;
  1549. }
  1550.  
  1551. function getFormatJSON(obj){
  1552. if(!objIsArr(obj))return "";
  1553. let ret="[\n";
  1554. let len=obj.length,i=0,isLast;
  1555. obj.forEach(item=>{
  1556. ret+=" {\n";
  1557. let iLen=Object.keys(item).length,j=0;
  1558. for(let key in item){
  1559. isLast=(++j)==iLen;
  1560. let value=item[key];
  1561. if(objIsArr(value)){
  1562. let vstr="[",v=0,vIsLast=false;
  1563. value.forEach(vi=>{
  1564. vIsLast=(++v)==value.length;
  1565. vstr+="\""+vi.replace(/\\/g,"\\\\")+"\""+(vIsLast?"":",");
  1566. });
  1567. vstr+="]";
  1568. ret+=" \""+key+"\":"+vstr+""+(isLast?"":",")+"\n";
  1569. }else{
  1570. if(typeof value=="string"){
  1571. value=value.replace(/\\/g,"\\\\").replace(/"/g,"\\\"");
  1572. value="\""+value+"\"";
  1573. }
  1574. ret+=" \""+key+"\":"+value+""+(isLast?"":",")+"\n";
  1575. }
  1576. }
  1577. isLast=(++i)==len;
  1578. ret+=" }"+(isLast?"":",")+"\n";
  1579. });
  1580. ret+="]";
  1581. return ret;
  1582. }
  1583.  
  1584. function initRules(callback) {
  1585. /*0 wedata格式,1 pagetual格式*/
  1586. ruleUrls=[
  1587. {
  1588. id:0,
  1589. url:'https://raw.githubusercontent.com/hoothin/UserScripts/master/Pagetual/pagetualRules.json',
  1590. type:1
  1591. },
  1592. {
  1593. id:1,
  1594. url:'http://wedata.net/databases/AutoPagerize/items_all.json',
  1595. type:0,
  1596. }
  1597. ];var i=0,j=0;
  1598.  
  1599. ruleParser.initSavedRules(()=>{
  1600. storage.getItem("rulesData", data=>{
  1601. if(data){
  1602. rulesData=data;
  1603. if(data.urls)ruleUrls=ruleUrls.concat(data.urls);
  1604. if(data.sort){
  1605. let urls=[];
  1606. data.sort.forEach(id=>{
  1607. for(let s=0;s<ruleUrls.length;s++){
  1608. if(id==ruleUrls[s].id){
  1609. urls.push(ruleUrls[s]);
  1610. break;
  1611. }
  1612. }
  1613. });
  1614. ruleUrls=urls;
  1615. }
  1616. }
  1617. if(typeof(rulesData.opacity)=="undefined"){
  1618. rulesData.opacity=0.3;
  1619. }
  1620. if(typeof(rulesData.hideBar)=="undefined"){
  1621. rulesData.hideBar=true;
  1622. }
  1623. if(typeof(rulesData.dbClick2Stop)=="undefined"){
  1624. rulesData.dbClick2Stop=true;
  1625. }
  1626. if(typeof(rulesData.enableWhiteList)=="undefined"){
  1627. rulesData.enableWhiteList=false;
  1628. }
  1629. if(typeof(rulesData.enableHistory)=="undefined"){
  1630. rulesData.enableHistory=true;
  1631. }
  1632. if(typeof(rulesData.enableDebug)=="undefined"){
  1633. rulesData.enableDebug=true;
  1634. }
  1635. if(typeof(rulesData.initRun)=="undefined"){
  1636. rulesData.initRun=true;
  1637. }
  1638. enableDebug=rulesData.enableDebug;
  1639. storage.getItem("forceState_"+location.host, v=>{
  1640. storage.getItem("ruleLastUpdate", date=>{
  1641. if(typeof(v)=="undefined"){
  1642. v=(rulesData.enableWhiteList?1:0);
  1643. }
  1644. forceState=v;
  1645. updateDate=date;
  1646. if(initConfig())return;
  1647. if(forceState==1)return;
  1648. let now=new Date().getTime();
  1649. if(!date || now-date>2*24*60*60*1000){
  1650. storage.setItem("ruleLastUpdate", now);
  1651. updateRules(()=>{
  1652. callback();
  1653. },(rule,err)=>{});
  1654. }else{
  1655. callback();
  1656. }
  1657. });
  1658. });
  1659. });
  1660. });
  1661. }
  1662.  
  1663. function requestDoc(url, callback){
  1664. _GM_xmlhttpRequest({
  1665. url: url,
  1666. method: 'GET',
  1667. overrideMimeType: 'text/html;charset='+document.charset,
  1668. headers: {
  1669. 'Referer': location.href
  1670. },
  1671. timeout: 5000,
  1672. onload: function(res) {
  1673. var doc=null;
  1674. try {
  1675. doc=document.implementation.createHTMLDocument('');
  1676. doc.documentElement.innerHTML=res.response;
  1677. }
  1678. catch (e) {
  1679. debug('parse error'+e.toString());
  1680. }
  1681. let pageElement=ruleParser.getPageElement(doc);
  1682. //只有1的話怕不是圖片哦
  1683. if(pageElement && (pageElement.length>1 || (pageElement.length==1 && pageElement[0].tagName!="IMG") )){
  1684. let result=ruleParser.insertPage(doc, pageElement, url, callback, false);
  1685. if(!result){
  1686. requestFromIframe(url, (doc, eles)=>{
  1687. loadPageOver();
  1688. if(eles){
  1689. ruleParser.insertPage(doc, eles, url, callback, true);
  1690. }
  1691. });
  1692. }
  1693. }else if(ruleParser.curSiteRule.singleUrl){
  1694. requestFromIframe(url, (doc, eles)=>{
  1695. loadPageOver();
  1696. if(eles){
  1697. ruleParser.insertPage(doc, eles, url, callback, true);
  1698. }
  1699. });
  1700. }else{
  1701. isPause=true;
  1702. callback(false);
  1703. }
  1704. },
  1705. onerror: function(e){
  1706. debug(e);
  1707. callback(false);
  1708. },
  1709. ontimeout: function(e){
  1710. debug(e);
  1711. callback(false);
  1712. }
  1713. });
  1714. }
  1715.  
  1716. var failFromIframe=0;
  1717. function requestFromIframe(url, callback){
  1718. let orgPage,curPage;
  1719. let iframe = document.createElement('iframe');
  1720. iframe.name = 'pagetual-iframe';
  1721. iframe.width = '100%';
  1722. iframe.height = '0';
  1723. iframe.frameBorder = '0';
  1724. if(ruleParser.curSiteRule.sandbox!=false){
  1725. iframe.sandbox="allow-same-origin allow-scripts allow-popups allow-forms";
  1726. }
  1727. iframe.style.cssText = 'margin:0!important;padding:0!important;visibility:hidden!important;';
  1728. iframe.addEventListener("load", e=>{
  1729. let waitTime=500,checkEval;
  1730. if(ruleParser.curSiteRule.wait){
  1731. if(isNaN(ruleParser.curSiteRule.wait)){
  1732. try{
  1733. checkEval=Function("doc",'"use strict";' + ruleParser.curSiteRule.wait);
  1734. }catch(e){
  1735. debug(e);
  1736. }
  1737. }else{
  1738. waitTime=ruleParser.curSiteRule.wait;
  1739. }
  1740. }
  1741. setTimeout(()=>{
  1742. let tryTimes=0;
  1743. function checkIframe(){
  1744. try{
  1745. let doc=iframe.contentDocument || iframe.contentWindow.document;
  1746. let eles=ruleParser.getPageElement(doc, iframe.contentWindow);
  1747. if(eles && eles.length>0 && (!checkEval || checkEval(doc))){
  1748. callback(doc, eles);
  1749. }else if(tryTimes++ < 10){
  1750. setTimeout(()=>{
  1751. checkIframe();
  1752. },waitTime);
  1753. return;
  1754. }else{
  1755. if(failFromIframe++ > 2){
  1756. failFromIframe=0;
  1757. debug("Stop as failFromIframe");
  1758. isPause=true;
  1759. callback(false, false);
  1760. }else{
  1761. callback(false, false);
  1762. }
  1763. }
  1764. }catch(e){
  1765. debug("Stop as cors");
  1766. //isPause=true;
  1767. ruleParser.curSiteRule.pageElement=allOfBody;
  1768. ruleParser.getInsert(true);
  1769. callback(false, false);
  1770. }
  1771. document.body.removeChild(iframe);
  1772. }
  1773. checkIframe();
  1774. },waitTime);
  1775. });
  1776. iframe.src=url;
  1777. document.body.appendChild(iframe);
  1778. }
  1779.  
  1780. function initPage(){
  1781. ruleParser.initPage(()=>{
  1782. if(ruleParser.nextLinkHref){
  1783. initView();
  1784. let isJs=/^(javascript|#)/.test(ruleParser.nextLinkHref.replace(location.href,""));
  1785. if(!isJs){
  1786. _GM_registerMenuCommand(i18n(forceState==2?"cancelForceIframe":"forceIframe"), ()=>{
  1787. storage.setItem("forceState_"+location.host, (forceState==2?"":2));
  1788. location.reload();
  1789. });
  1790. }
  1791. _GM_registerMenuCommand(i18n("loadNow"), ()=>{
  1792. let loadNum=window.prompt(i18n("loadConfirm"), "1");
  1793. if(loadNum==="" || loadNum===null)return;
  1794. autoLoadNum=Math.abs(parseInt(loadNum));
  1795. nextPage();
  1796. });
  1797. }
  1798. initListener();
  1799. if(rulesData.initRun)nextPage();
  1800. });
  1801. }
  1802.  
  1803. function initView(){
  1804. _GM_addStyle(`
  1805. .pagetual_pageBar.stop {
  1806. -webkit-filter: invert(100%);
  1807. filter: invert(100%);
  1808. opacity: 1!important;
  1809. }
  1810. .pagetual_pageBar.hide {
  1811. display: none!important;
  1812. }
  1813. .pagetual_pageBar:hover {
  1814. opacity: 1!important;
  1815. }
  1816. .pagetual_pageBar span {
  1817. vertical-align: super;
  1818. }
  1819.  
  1820. .pagetual_pageBar span>svg:hover {
  1821. animation: touhouAni 1s infinite;
  1822. }
  1823. .pagetual_pageBar .pagetual_pageNum{
  1824. color: #55555f;
  1825. }
  1826. .pagetual_pageBar .pagetual_pageNum:hover{
  1827. color: #ff6464;
  1828. }
  1829.  
  1830. @keyframes touhouAni{
  1831. from {transform: rotate(0deg) scale3d(1.2, 1.2, 1.2);}
  1832. to {transform: rotate(360deg);}
  1833. }
  1834. @-webkit-keyframes touhouAni{
  1835. from {transform: rotate(0deg) scale3d(1.2, 1.2, 1.2);}
  1836. to {transform: rotate(360deg);}
  1837. }
  1838. `);
  1839. pageBarStyle=`opacity:${rulesData.opacity};display:${rulesData.opacity==0?"none":"block"};padding:0;box-shadow: 0px 0px 10px 0px #000000aa;border-radius: 20px;background-color: rgb(240 240 240 / 80%);visibility: visible; position: initial; width: auto; height: 30px; float: none; clear: both; margin: 5px auto; text-align: center;`;
  1840. }
  1841. var loadingDiv=document.createElement("div");
  1842. loadingDiv.className="pagetual_loading";
  1843. loadingDiv.style.cssText="cy: initial;d: initial;dominant-baseline: initial;empty-cells: initial;fill: initial;fill-opacity: initial;fill-rule: initial;filter: initial;flex: initial;flex-flow: initial;float: initial;flood-color: initial;flood-opacity: initial;grid: initial;grid-area: initial;height: initial;hyphens: initial;image-orientation: initial;image-rendering: initial;inline-size: initial;inset-block: initial;inset-inline: initial;isolation: initial;letter-spacing: initial;lighting-color: initial;line-break: initial;list-style: initial;margin-block: initial;margin: 0px auto;margin-inline: initial;marker: initial;mask: initial;mask-type: initial;max-block-size: initial;max-height: initial;max-inline-size: initial;max-width: initial;min-block-size: initial;min-height: initial;min-inline-size: initial;min-width: initial;mix-blend-mode: initial;object-fit: initial;object-position: initial;offset: initial;opacity: initial;order: initial;origin-trial-test-property: initial;orphans: initial;outline: initial;outline-offset: initial;overflow-anchor: initial;overflow-clip-margin: initial;overflow-wrap: initial;overflow: initial;overscroll-behavior-block: initial;overscroll-behavior-inline: initial;overscroll-behavior: initial;padding-block: initial;padding: initial;padding-inline: initial;page: initial;page-orientation: initial;paint-order: initial;perspective: initial;perspective-origin: initial;pointer-events: initial;position: initial;quotes: initial;r: initial;resize: initial;ruby-position: initial;rx: initial;ry: initial;scroll-behavior: initial;scroll-margin-block: initial;scroll-margin: initial;scroll-margin-inline: initial;scroll-padding-block: initial;scroll-padding: initial;scroll-padding-inline: initial;scroll-snap-align: initial;scroll-snap-stop: initial;scroll-snap-type: initial;scrollbar-gutter: initial;shape-image-threshold: initial;shape-margin: initial;shape-outside: initial;shape-rendering: initial;size: initial;speak: initial;stop-color: initial;stop-opacity: initial;stroke: initial;stroke-dasharray: initial;stroke-dashoffset: initial;stroke-linecap: initial;stroke-linejoin: initial;stroke-miterlimit: initial;stroke-opacity: initial;stroke-width: initial;tab-size: initial;table-layout: initial;text-align: initial;text-align-last: initial;text-anchor: initial;text-combine-upright: initial;text-decoration: initial;text-decoration-skip-ink: initial;text-indent: initial;text-overflow: initial;text-shadow: initial;text-size-adjust: initial;text-transform: initial;text-underline-offset: initial;text-underline-position: initial;touch-action: initial;transform: initial;transform-box: initial;transform-origin: initial;transform-style: initial;transition: initial;user-select: initial;vector-effect: initial;vertical-align: initial;visibility: initial;border-spacing: initial;-webkit-border-image: initial;-webkit-box-align: initial;-webkit-box-decoration-break: initial;-webkit-box-direction: initial;-webkit-box-flex: initial;-webkit-box-ordinal-group: initial;-webkit-box-orient: initial;-webkit-box-pack: initial;-webkit-box-reflect: initial;-webkit-highlight: initial;-webkit-hyphenate-character: initial;-webkit-line-break: initial;-webkit-line-clamp: initial;-webkit-mask-box-image: initial;-webkit-mask: initial;-webkit-mask-composite: initial;-webkit-perspective-origin-x: initial;-webkit-perspective-origin-y: initial;-webkit-print-color-adjust: initial;-webkit-rtl-ordering: initial;-webkit-ruby-position: initial;-webkit-tap-highlight-color: initial;-webkit-text-combine: initial;-webkit-text-decorations-in-effect: initial;-webkit-text-emphasis: initial;-webkit-text-emphasis-position: initial;-webkit-text-fill-color: initial;-webkit-text-security: initial;-webkit-text-stroke: initial;-webkit-transform-origin-x: initial;-webkit-transform-origin-y: initial;-webkit-transform-origin-z: initial;-webkit-user-drag: initial;-webkit-user-modify: initial;white-space: initial;widows: initial;width: initial;will-change: initial;word-break: initial;word-spacing: initial;x: initial;y: initial;z-index: 2147483647;";
  1844. loadingDiv.innerHTML=`<p style=" display: block; position: initial; margin: auto auto 5px auto; shape-rendering: auto; vertical-align: middle; visibility: visible; width: initial; height: initial; text-align: center; color: #6e6e6e; ">${i18n("loadingText")}</p><svg width="120" height="30" viewBox="0 0 120 30" fill="#000000A0" style="display: block;position: initial;margin: auto;shape-rendering: auto;vertical-align: middle;visibility: visible;width: initial;height: initial;"><circle cx="15" cy="15" r="15"><animate attributeName="r" from="15" to="15" begin="0s" dur="0.8s" values="15;9;15" calcMode="linear" repeatCount="indefinite"></animate><animate attributeName="fill-opacity" from="1" to="1" begin="0s" dur="0.8s" values="1;.5;1" calcMode="linear" repeatCount="indefinite"></animate></circle><circle cx="60" cy="15" r="9" fill-opacity="0.3"><animate attributeName="r" from="9" to="9" begin="0s" dur="0.8s" values="9;15;9" calcMode="linear" repeatCount="indefinite"></animate><animate attributeName="fill-opacity" from="0.5" to="0.5" begin="0s" dur="0.8s" values=".5;1;.5" calcMode="linear" repeatCount="indefinite"></animate></circle><circle cx="105" cy="15" r="15"><animate attributeName="r" from="15" to="15" begin="0s" dur="0.8s" values="15;9;15" calcMode="linear" repeatCount="indefinite"></animate><animate attributeName="fill-opacity" from="1" to="1" begin="0s" dur="0.8s" values="1;.5;1" calcMode="linear" repeatCount="indefinite"></animate></circle></svg>`;
  1845.  
  1846. var upSvg=`<svg width="30" height="30" style="position:absolute;cursor: pointer;margin: 0 -45px;width: 30px;height: 30px;vertical-align: middle;fill: currentColor;overflow: hidden;" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="6364"><path d="M296 440c-44.1 0-80 35.9-80 80s35.9 80 80 80 80-35.9 80-80-35.9-80-80-80z" fill="#604b4a" p-id="6365"></path><path d="M960 512c0-247-201-448-448-448S64 265 64 512c0 1.8 0.1 3.5 0.1 5.3 0 0.9-0.1 1.8-0.1 2.7h0.2C68.5 763.3 267.7 960 512 960c236.2 0 430.1-183.7 446.7-415.7 0.1-0.8 0.1-1.6 0.2-2.3 0.4-4.6 0.5-9.3 0.7-13.9 0.1-2.7 0.4-5.3 0.4-8h-0.2c0-2.8 0.2-5.4 0.2-8.1z m-152 8c0 44.1-35.9 80-80 80s-80-35.9-80-80 35.9-80 80-80 80 35.9 80 80zM512 928C284.4 928 99 744.3 96.1 517.3 97.6 408.3 186.6 320 296 320c110.3 0 200 89.7 200 200 0 127.9 104.1 232 232 232 62.9 0 119.9-25.2 161.7-66-66 142.7-210.4 242-377.7 242z" fill="#604b4a" p-id="6366"></path></svg>`;
  1847. var downSvg=`<svg width="30" height="30" style="position:absolute;cursor: pointer;margin: 0 15px;width: 30px;height: 30px;vertical-align: middle;fill: currentColor;overflow: hidden;transform: rotate(180deg);" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="6364"><path d="M296 440c-44.1 0-80 35.9-80 80s35.9 80 80 80 80-35.9 80-80-35.9-80-80-80z" fill="#604b4a" p-id="6365"></path><path d="M960 512c0-247-201-448-448-448S64 265 64 512c0 1.8 0.1 3.5 0.1 5.3 0 0.9-0.1 1.8-0.1 2.7h0.2C68.5 763.3 267.7 960 512 960c236.2 0 430.1-183.7 446.7-415.7 0.1-0.8 0.1-1.6 0.2-2.3 0.4-4.6 0.5-9.3 0.7-13.9 0.1-2.7 0.4-5.3 0.4-8h-0.2c0-2.8 0.2-5.4 0.2-8.1z m-152 8c0 44.1-35.9 80-80 80s-80-35.9-80-80 35.9-80 80-80 80 35.9 80 80zM512 928C284.4 928 99 744.3 96.1 517.3 97.6 408.3 186.6 320 296 320c110.3 0 200 89.7 200 200 0 127.9 104.1 232 232 232 62.9 0 119.9-25.2 161.7-66-66 142.7-210.4 242-377.7 242z" fill="#604b4a" p-id="6366"></path></svg>`;
  1848. var pageBarStyle;
  1849. var initStyle=`display: initial;right: unset;left: unset;top: unset;bottom: unset;inset: unset;clear: both;cy: initial;d: initial;dominant-baseline: initial;empty-cells: initial;fill: initial;fill-opacity: initial;fill-rule: initial;filter: initial;flex: initial;flex-flow: initial;float: initial;flood-color: initial;flood-opacity: initial;grid: initial;grid-area: initial;height: initial;hyphens: initial;image-orientation: initial;image-rendering: initial;inline-size: initial;inset-block: initial;inset-inline: initial;isolation: initial;letter-spacing: initial;lighting-color: initial;line-break: initial;list-style: initial;margin-block: initial;margin: 0px auto;margin-inline: initial;marker: initial;mask: initial;mask-type: initial;max-block-size: initial;max-height: initial;max-inline-size: initial;max-width: initial;min-block-size: initial;min-height: initial;min-inline-size: initial;min-width: initial;mix-blend-mode: initial;object-fit: initial;object-position: initial;offset: initial;opacity: initial;order: initial;orphans: initial;outline: initial;outline-offset: initial;overflow-anchor: initial;overflow-clip-margin: initial;overflow-wrap: initial;overflow: initial;overscroll-behavior-block: initial;overscroll-behavior-inline: initial;overscroll-behavior: initial;padding-block: initial;padding: initial;padding-inline: initial;page: initial;page-orientation: initial;paint-order: initial;perspective: initial;perspective-origin: initial;pointer-events: initial;position: initial;quotes: initial;r: initial;resize: initial;ruby-position: initial;rx: initial;ry: initial;scroll-behavior: initial;scroll-margin-block: initial;scroll-margin: initial;scroll-margin-inline: initial;scroll-padding-block: initial;scroll-padding: initial;scroll-padding-inline: initial;scroll-snap-align: initial;scroll-snap-stop: initial;scroll-snap-type: initial;scrollbar-gutter: initial;shape-image-threshold: initial;shape-margin: initial;shape-outside: initial;shape-rendering: initial;size: initial;speak: initial;stop-color: initial;stop-opacity: initial;stroke: initial;stroke-dasharray: initial;stroke-dashoffset: initial;stroke-linecap: initial;stroke-linejoin: initial;stroke-miterlimit: initial;stroke-opacity: initial;stroke-width: initial;tab-size: initial;table-layout: initial;text-align: initial;text-align-last: initial;text-anchor: initial;text-combine-upright: initial;text-decoration: initial;text-decoration-skip-ink: initial;text-indent: initial;text-overflow: initial;text-shadow: initial;text-size-adjust: initial;text-transform: initial;text-underline-offset: initial;text-underline-position: initial;touch-action: initial;transform: initial;transform-box: initial;transform-origin: initial;transform-style: initial;transition: initial;user-select: initial;vector-effect: initial;vertical-align: initial;visibility: initial;border-spacing: initial;-webkit-border-image: initial;-webkit-box-align: initial;-webkit-box-decoration-break: initial;-webkit-box-direction: initial;-webkit-box-flex: initial;-webkit-box-ordinal-group: initial;-webkit-box-orient: initial;-webkit-box-pack: initial;-webkit-box-reflect: initial;-webkit-highlight: initial;-webkit-hyphenate-character: initial;-webkit-line-break: initial;-webkit-line-clamp: initial;-webkit-mask-box-image: initial;-webkit-mask: initial;-webkit-mask-composite: initial;-webkit-perspective-origin-x: initial;-webkit-perspective-origin-y: initial;-webkit-print-color-adjust: initial;-webkit-rtl-ordering: initial;-webkit-ruby-position: initial;-webkit-tap-highlight-color: initial;-webkit-text-combine: initial;-webkit-text-decorations-in-effect: initial;-webkit-text-emphasis: initial;-webkit-text-emphasis-position: initial;-webkit-text-fill-color: initial;-webkit-text-security: initial;-webkit-text-stroke: initial;-webkit-transform-origin-x: initial;-webkit-transform-origin-y: initial;-webkit-transform-origin-z: initial;-webkit-user-drag: initial;-webkit-user-modify: initial;white-space: initial;widows: initial;width: initial;will-change: initial;word-break: initial;word-spacing: initial;x: initial;y: initial;`;
  1850. var pageTextStyle=`line-height: 30px;text-decoration: none;user-select: none;visibility: visible;position: initial;width: auto;height: auto;float: none;clear: both;margin: 0px auto;text-align: center;display: inline;font-weight: bold;font-style: normal;font-size: 16px;letter-spacing: initial;vertical-align: super;color: rgb(85, 85, 95);`;
  1851.  
  1852. var isPause=false,isLoading=false,curPage=1,forceState=0,bottomGap=1000,autoLoadNum=-1;
  1853.  
  1854. function changeStop(stop, hide){
  1855. isPause=stop;
  1856. [].forEach.call(document.querySelectorAll(".pagetual_pageBar"), bar=>{
  1857. if(isPause){
  1858. bar.classList.add("stop");
  1859. if(hide)bar.classList.add("hide");
  1860. }else{
  1861. bar.classList.remove("stop");
  1862. if(hide)bar.classList.remove("hide");
  1863. }
  1864. });
  1865. }
  1866.  
  1867. function isInViewPort(element) {
  1868. if(!element.parentNode)return false;
  1869. if(_unsafeWindow.getComputedStyle(element).display=="none")return false;
  1870. const viewWidth = window.innerWidth || document.documentElement.clientWidth;
  1871. const viewHeight = window.innerHeight || document.documentElement.clientHeight;
  1872. const {
  1873. top,
  1874. right,
  1875. bottom,
  1876. left,
  1877. } = element.getBoundingClientRect();
  1878.  
  1879. return (
  1880. top >= 0 &&
  1881. left >= 0 &&
  1882. right <= viewWidth &&
  1883. bottom <= viewHeight
  1884. );
  1885. }
  1886.  
  1887. var urlChanged=false;
  1888. var _wr = function(type) {
  1889. var orig = history[type];
  1890. return function() {
  1891. var rv = orig.apply(this, arguments);
  1892. var e = new Event(type);
  1893. e.arguments = arguments;
  1894. window.dispatchEvent(e);
  1895. return rv;
  1896. };
  1897. };
  1898. history.pushState = _wr('pushState');
  1899. window.addEventListener('pushState', function(e) {
  1900. urlChanged=true;
  1901. isPause=true;
  1902. setTimeout(()=>{
  1903. if(location.href==configPage){
  1904. location.reload();
  1905. }
  1906. },1);
  1907. });
  1908.  
  1909. function initListener(){
  1910. let loadmoreBtn,loading=true;
  1911. setTimeout(()=>{
  1912. loadmoreBtn=getLoadMore(document);
  1913. if(loadmoreBtn && isVisible(loadmoreBtn, _unsafeWindow)){
  1914. loading=false;
  1915. }
  1916. },500);
  1917. let checkScrollReach=()=>{
  1918. let scrolly=window.scrollY;
  1919. let windowHeight=window.innerHeight || document.documentElement.clientHeight;
  1920. let scrollH=Math.max(document.documentElement.scrollHeight, document.body.scrollHeight);
  1921. if(scrollH-scrolly-windowHeight<bottomGap){
  1922. nextPage();
  1923. }
  1924. };
  1925. document.addEventListener('scroll', e=>{
  1926. if(urlChanged){
  1927. ruleParser.initPage(()=>{
  1928. if(ruleParser.nextLinkHref)initView();
  1929. });
  1930. urlChanged=false;
  1931. isPause=false;
  1932. }
  1933. if(isPause)return;
  1934. if(!loading){
  1935. loading=true;
  1936. setTimeout(()=>{loading=false},200);
  1937. if(!loadmoreBtn || !loadmoreBtn.parentNode){
  1938. loadmoreBtn=getLoadMore(document);
  1939. }
  1940. if(loadmoreBtn){
  1941. if(isInViewPort(loadmoreBtn)){
  1942. emuClick(loadmoreBtn);
  1943. }
  1944. }
  1945. }
  1946. setTimeout(()=>{
  1947. if(!isLoading){
  1948. checkScrollReach();
  1949. }
  1950. },100);
  1951. }, true);
  1952. document.addEventListener('dblclick', e=>{
  1953. if(rulesData.dbClick2Stop){
  1954. setTimeout(()=>{
  1955. changeStop(!isPause, rulesData.hideBar);
  1956. if(!isPause){
  1957. checkScrollReach();
  1958. }
  1959. },200);
  1960. }
  1961. });
  1962. }
  1963.  
  1964. function getLoadMore(doc){
  1965. if(ruleParser.curSiteRule.loadMore==="")return null;
  1966. let btnSel=ruleParser.curSiteRule.loadMore||".LoadMore,.load-more";
  1967. let loadmoreBtn=doc.querySelector(btnSel);
  1968. if(!loadmoreBtn){
  1969. let buttons=doc.querySelectorAll("input,button,a,div[onclick]"),loadmoreReg=/^\s*(加载更多|加載更多|load\s*more|もっと読み込む)\s*$/i;
  1970. for(let i=0;i<buttons.length;i++){
  1971. let button=buttons[i];
  1972. if(button && loadmoreReg.test(button.innerText)){
  1973. loadmoreBtn=button;
  1974. break;
  1975. }
  1976. }
  1977. }
  1978. return loadmoreBtn;
  1979. }
  1980.  
  1981. var hasPageNum=true;
  1982. function createPageBar(url){
  1983. let insert=ruleParser.getInsert();
  1984. if(!insert || !insert.parentNode)return;
  1985. curPage++;
  1986. if(rulesData.opacity==0)return;
  1987. let example=ruleParser.curSiteRule.insertPos==2?insert.children[0]:(insert.previousElementSibling||insert);
  1988. if(!example || !example.parentNode)example=insert;
  1989. let inTable=example.parentNode.tagName=="TABLE" ||
  1990. example.tagName=="TR" ||
  1991. example.tagName=="TBODY" ||
  1992. (example.previousElementSibling && example.previousElementSibling.tagName=="TR") ||
  1993. (example.previousElementSibling && example.previousElementSibling.tagName=="TBODY");
  1994. let inLi=example.tagName=="LI" || (example.previousElementSibling && example.previousElementSibling.tagName=="LI");
  1995. let pageBar=document.createElement(inTable?"tr":(inLi?"li":"div"));
  1996. let upSpan=document.createElement("span");
  1997. let downSpan=document.createElement("span");
  1998. let pageText=document.createElement("a");
  1999. let pageNum;
  2000. pageBar.className="pagetual_pageBar";
  2001. pageBar.id="pagetual_pageBar";
  2002. if(isPause){
  2003. pageBar.classList.add("stop");
  2004. }
  2005. pageBar.style.cssText=pageBarStyle;
  2006. pageBar.title=i18n(isPause?"enable":"disable");
  2007. upSpan.innerHTML=upSvg;
  2008. upSpan.title=i18n("toTop");
  2009. downSpan.innerHTML=downSvg;
  2010. downSpan.title=i18n("toBottom");
  2011. upSpan.style.cssText=initStyle;
  2012. downSpan.style.cssText=initStyle;
  2013. pageText.href=url;
  2014. pageText.style.cssText=pageTextStyle;
  2015. pageText.title=i18n("current");
  2016. pageBar.appendChild(upSpan);
  2017. pageBar.appendChild(pageText);
  2018. if(ruleParser.curSiteRule.pageNum || (hasPageNum && /[&\/\?](p=|page[=\/])\d+/.test(url))){
  2019. pageText.innerHTML="Page ";
  2020. pageNum=document.createElement("span");
  2021. pageNum.innerText=curPage;
  2022. pageNum.className="pagetual_pageNum";
  2023. pageNum.title=i18n("inputPageNum");
  2024. pageNum.style.cssText=pageTextStyle;
  2025. pageNum.style.cursor="pointer";
  2026. pageNum.style.color="";
  2027. pageNum.addEventListener("click", e=>{
  2028. let pageInput=prompt(i18n("inputPageNum"));
  2029. if(pageInput){
  2030. let pageLink=ruleParser.getLinkByPage(url, pageInput);
  2031. if(pageLink){
  2032. _GM_openInTab(pageLink,{active:true});
  2033. }
  2034. }
  2035. e.preventDefault();
  2036. e.stopPropagation();
  2037. });
  2038. pageBar.appendChild(pageNum);
  2039. }else{
  2040. pageText.innerHTML="Page "+curPage;
  2041. hasPageNum=false;
  2042. }
  2043. pageBar.appendChild(downSpan);
  2044. let parentStyle=_unsafeWindow.getComputedStyle(example.parentNode);
  2045. pageBar.style.width=parentStyle.width;
  2046. if(parentStyle.display=="grid" || parentStyle.display=="inline-grid"){
  2047. pageBar.style.gridColumnStart=1;
  2048. pageBar.style.gridColumnEnd=1+parseInt(example.parentNode.offsetWidth/example.offsetWidth);
  2049. }
  2050. if(inTable){
  2051. example=(example.tagName=="TR" || example.tagName=="TBODY")?example:example.previousElementSibling;
  2052. if(example.previousElementSibling)example=example.previousElementSibling;
  2053. let tdNum=0;
  2054. [].forEach.call(example.querySelectorAll("td,th"), td=>{
  2055. tdNum+=td.colSpan||1;
  2056. });
  2057. pageBar.style.display="table-row";
  2058. pageBar.style.backgroundColor="unset";
  2059. let td=document.createElement("td");
  2060. td.style.backgroundColor="rgb(240 240 240 / 80%)";
  2061. td.style.borderRadius="20px";
  2062. td.colSpan=tdNum||1;
  2063. td.style.padding="0 0";
  2064. td.style.textAlign="center";
  2065. td.appendChild(upSpan);
  2066. td.appendChild(pageText);
  2067. if(pageNum)td.appendChild(pageNum);
  2068. td.appendChild(downSpan);
  2069. pageBar.appendChild(td);
  2070. }else if(inLi){
  2071. example=example.tagName=="LI"?example:example.previousElementSibling;
  2072. pageBar.style.display="table-row";
  2073. pageBar.style.backgroundColor="unset";
  2074. let td=document.createElement("td");
  2075. td.style.backgroundColor="rgb(240 240 240 / 80%)";
  2076. td.style.borderRadius="20px";
  2077. td.colSpan=example.children.length;
  2078. td.style.padding="0 0";
  2079. td.style.textAlign="center";
  2080. td.style.minWidth="150px";
  2081. td.appendChild(upSpan);
  2082. td.appendChild(pageText);
  2083. td.style.width=pageBar.style.width;
  2084. if(pageNum)td.appendChild(pageNum);
  2085. td.appendChild(downSpan);
  2086. pageBar.appendChild(td);
  2087. }
  2088.  
  2089. upSpan.addEventListener("click", e=>{
  2090. document.body.scrollTop=0;
  2091. document.documentElement.scrollTop=0;
  2092. e.preventDefault();
  2093. e.stopPropagation();
  2094. });
  2095. downSpan.addEventListener("click", e=>{
  2096. changeStop(true);
  2097. pageBar.title=i18n(isPause?"enable":"disable");
  2098. document.body.scrollTop=9999999;
  2099. document.documentElement.scrollTop=9999999;
  2100. e.preventDefault();
  2101. e.stopPropagation();
  2102. });
  2103. pageBar.addEventListener("click", e=>{
  2104. changeStop(!isPause);
  2105. pageBar.title=i18n(isPause?"enable":"disable");
  2106. });
  2107. pageText.addEventListener("click", e=>{
  2108. e.stopPropagation();
  2109. });
  2110. if(ruleParser.curSiteRule.insertPos==2){
  2111. insert.appendChild(pageBar);
  2112. }else{
  2113. insert.parentNode.insertBefore(pageBar, insert);
  2114. }
  2115. if(ruleParser.curSiteRule.pageBar){
  2116. try{
  2117. Function("pageBar",'"use strict";' + ruleParser.curSiteRule.pageBar)(pageBar);
  2118. }catch(e){
  2119. debug(e);
  2120. }
  2121. }
  2122.  
  2123. let scrollH=Math.max(document.documentElement.scrollHeight, document.body.scrollHeight);
  2124. let posEle=pageBar.nextElementSibling||pageBar;
  2125. while(posEle && !posEle.offsetParent){
  2126. posEle=posEle.previousElementSibling||posEle.parentNode;
  2127. }
  2128. if(posEle){
  2129. let actualTop = posEle.offsetTop;
  2130. let current = posEle.parentNode.offsetParent;
  2131. while (current !== null){
  2132. actualTop += current.offsetTop;
  2133. current = current.offsetParent;
  2134. }
  2135. bottomGap=scrollH-actualTop+(window.innerHeight||document.documentElement.clientHeight)*(ruleParser.curSiteRule.rate||1);
  2136. }else{
  2137. bottomGap=1000;
  2138. }
  2139. return pageBar;
  2140. }
  2141.  
  2142. function emuClick(btn){
  2143. if(!PointerEvent)return btn.click();
  2144. let eventParam={
  2145. isTrusted: true,
  2146. altKey: false,
  2147. azimuthAngle: 0,
  2148. bubbles: true,
  2149. button: 0,
  2150. buttons: 0,
  2151. clientX: 1,
  2152. clientY: 1,
  2153. cancelBubble: false,
  2154. cancelable: true,
  2155. composed: true,
  2156. ctrlKey: false,
  2157. defaultPrevented: false,
  2158. detail: 1,
  2159. eventPhase: 2,
  2160. fromElement: null,
  2161. height: 1,
  2162. isPrimary: false,
  2163. metaKey: false,
  2164. pointerId: 1,
  2165. pointerType: "mouse",
  2166. pressure: 0,
  2167. relatedTarget: null,
  2168. returnValue: true,
  2169. shiftKey: false,
  2170. toElement: null,
  2171. twist: 0,
  2172. type: "click",
  2173. which: 1
  2174. };
  2175. var mouseclick = new PointerEvent("click",eventParam);
  2176. btn.dispatchEvent(mouseclick);
  2177. }
  2178.  
  2179. var emuIframe;
  2180. function emuPage(callback){
  2181. let orgPage,curPage,iframeDoc,times=0,loadmoreBtn,loadmoreEnd=false,waitTimes=10;
  2182. function checkPage(){
  2183. if(isPause)return;
  2184. try{
  2185. iframeDoc=emuIframe.contentDocument || emuIframe.contentWindow.document;
  2186. }catch(e){
  2187. debug("Stop as cors");
  2188. isPause=true;
  2189. callback(false, false);
  2190. return;
  2191. }
  2192.  
  2193. let nextLink=ruleParser.getNextLink(iframeDoc);
  2194. let waitTime=500,checkEval;
  2195. if(ruleParser.curSiteRule.wait){
  2196. if(isNaN(ruleParser.curSiteRule.wait)){
  2197. try{
  2198. checkEval=Function("doc",'"use strict";' + ruleParser.curSiteRule.wait);
  2199. }catch(e){
  2200. debug(e);
  2201. }
  2202. }else{
  2203. waitTime=ruleParser.curSiteRule.wait;
  2204. }
  2205. }
  2206.  
  2207. if(!orgPage){
  2208. if(!loadmoreEnd){
  2209. loadmoreBtn=getLoadMore(iframeDoc);
  2210. if(loadmoreBtn && isVisible(loadmoreBtn, iframeDoc.defaultView)){
  2211. emuClick(loadmoreBtn);
  2212. let intv=setInterval(()=>{
  2213. loadmoreBtn=getLoadMore(iframeDoc);
  2214. if(!loadmoreBtn || !loadmoreBtn.parentNode || !isVisible(loadmoreBtn, iframeDoc.defaultView)){
  2215. clearInterval(intv);
  2216. loadmoreEnd=true;
  2217. setTimeout(()=>{
  2218. checkPage();
  2219. },500);
  2220. }else{
  2221. emuClick(loadmoreBtn);
  2222. }
  2223. },200);
  2224. return;
  2225. }else{
  2226. loadmoreEnd=true;
  2227. }
  2228. }
  2229. let pageEle=ruleParser.getPageElement(iframeDoc, iframeDoc.defaultView, true);
  2230. if(!nextLink || !pageEle || (checkEval && !checkEval(iframeDoc))){
  2231. if(ruleParser.curSiteRule.wait && waitTimes-->0){
  2232. setTimeout(()=>{
  2233. checkPage();
  2234. },waitTime);
  2235. return;
  2236. }
  2237. }
  2238. orgPage=pageEle;
  2239. if(!orgPage || orgPage.length==0){
  2240. debug("Stop as no page when emu");
  2241. isPause=true;
  2242. callback(false, false);
  2243. return;
  2244. }
  2245. if(orgPage && orgPage[0].tagName=="UL")orgPage=orgPage[0].children;
  2246. if(orgPage && nextLink){
  2247. orgPage=orgPage[parseInt(orgPage.length/2)];
  2248. if(!isVisible(nextLink, iframeDoc.defaultView)){
  2249. debug("Stop as next hide when emu");
  2250. isPause=true;
  2251. callback(false, false);
  2252. }else{
  2253. emuClick(nextLink);
  2254. setTimeout(()=>{
  2255. checkPage();
  2256. },500);
  2257. }
  2258. }else{
  2259. debug("Stop as no next when emu");
  2260. isPause=true;
  2261. callback(false, false);
  2262. }
  2263. return;
  2264. }
  2265. if(times++ > 20){
  2266. //emuClick(nextLink);
  2267. debug("Stop as timeout when emu");
  2268. isPause=true;
  2269. callback(false, false);
  2270. return;
  2271. }
  2272. let eles=ruleParser.getPageElement(iframeDoc, iframeDoc.defaultView, true),checkItem=eles;
  2273. if(eles && eles.length>0 && eles[0].tagName=="UL")checkItem=eles[0].children;
  2274. if(!eles || eles.length==0 || orgPage == checkItem[parseInt(checkItem.length/2)] || (checkEval && !checkEval(iframeDoc))){
  2275. setTimeout(()=>{
  2276. checkPage();
  2277. },waitTime);
  2278. }else{
  2279. callback(iframeDoc, eles);
  2280. }
  2281. }
  2282. if(!emuIframe){
  2283. emuIframe = document.createElement('iframe');
  2284. emuIframe.name = 'pagetual-iframe';
  2285. if(ruleParser.curSiteRule.sandbox!=false){
  2286. emuIframe.sandbox="allow-same-origin allow-scripts allow-popups allow-forms";
  2287. }
  2288. emuIframe.width = '100%';
  2289. emuIframe.height = '0';
  2290. emuIframe.frameBorder = '0';
  2291. emuIframe.style.cssText = 'margin:0!important;padding:0!important;visibility:hidden!important;';
  2292. emuIframe.addEventListener("load", e=>{
  2293. setTimeout(()=>{
  2294. try{
  2295. iframeDoc=emuIframe.contentDocument || emuIframe.contentWindow.document;
  2296. }catch(e){
  2297. debug("Stop as cors");
  2298. isPause=true;
  2299. callback(false, false);
  2300. return;
  2301. }
  2302. let code=ruleParser.curSiteRule.init;
  2303. if(code){
  2304. try{
  2305. Function('doc','"use strict";' + code)(iframeDoc);
  2306. }catch(e){
  2307. debug(e);
  2308. }
  2309. }
  2310. checkPage();
  2311. },500);
  2312. });
  2313. emuIframe.src=location.href;
  2314. document.body.appendChild(emuIframe);
  2315. }else{
  2316. checkPage();
  2317. }
  2318. }
  2319.  
  2320. function forceIframe(url, callback){
  2321. let curIframe = document.createElement('iframe'),iframeDoc;
  2322. curIframe.name = 'pagetual-iframe';
  2323. curIframe.sandbox="allow-same-origin allow-scripts allow-popups allow-forms";
  2324. curIframe.frameBorder = '0';
  2325. curIframe.scrolling="no";
  2326. curIframe.style.cssText = 'display: block; visibility: visible; float: none; clear: both; width: 100%;height:0;background: initial; border: 0px; border-radius: 0px; margin: 0px 0px 2rem; padding: 0px; z-index: 2147483647;';
  2327. curIframe.addEventListener("load", e=>{
  2328. try{
  2329. iframeDoc=curIframe.contentDocument || curIframe.contentWindow.document;
  2330. }catch(e){
  2331. debug("Stop as cors");
  2332. isPause=true;
  2333. callback(false, false);
  2334. return;
  2335. }
  2336. ruleParser.insertPage(iframeDoc, [], url, null, true);
  2337. callback(curIframe, true);
  2338. curIframe.style.height=iframeDoc.body.scrollHeight+"px";
  2339. curIframe.style.width=iframeDoc.body.scrollWidth+"px";
  2340. });
  2341. let inAction=false;
  2342. let forceRefresh=e=>{
  2343. if(inAction || !iframeDoc)return;
  2344. inAction=true;
  2345. setTimeout(()=>{
  2346. inAction=false;
  2347. curIframe.style.height=iframeDoc.body.scrollHeight+"px";
  2348. curIframe.style.width=iframeDoc.body.scrollWidth+"px";
  2349. if(!ruleParser.nextLinkHref){
  2350. ruleParser.getNextLink(iframeDoc);
  2351. if(ruleParser.nextLinkHref){
  2352. document.removeEventListener("scroll", forceRefresh);
  2353. }
  2354. }else{
  2355. document.removeEventListener("scroll", forceRefresh);
  2356. }
  2357. },500);
  2358. curIframe.style.height=iframeDoc.body.scrollHeight+"px";
  2359. curIframe.style.width=iframeDoc.body.scrollWidth+"px";
  2360. };
  2361. document.addEventListener("scroll", forceRefresh);
  2362. curIframe.src=url;
  2363. let insert=ruleParser.getInsert();
  2364. document.body.appendChild(curIframe);
  2365. return curIframe;
  2366. }
  2367.  
  2368. function loadPageOver(){
  2369. isLoading=false;
  2370. if(loadingDiv.parentNode){
  2371. loadingDiv.parentNode.removeChild(loadingDiv);
  2372. }
  2373. setTimeout(()=>{
  2374. let scrollH=Math.max(document.documentElement.scrollHeight, document.body.scrollHeight);
  2375. if(scrollH < (window.innerHeight || document.documentElement.clientHeight)){
  2376. nextPage();
  2377. }
  2378. },1);
  2379. }
  2380.  
  2381. function nextPage(){
  2382. if(isPause || isLoading)return;
  2383. let nextLink=ruleParser.nextLinkHref;
  2384. if(!nextLink)return;
  2385. let insert=ruleParser.getInsert();
  2386. if(insert){
  2387. let isJs=/^(javascript|#)/.test(nextLink.replace(location.href,""));
  2388. if(location.protocol=="https:" && /^http:/.test(nextLink)){
  2389. nextLink=nextLink.replace(/^http/,"https");
  2390. }
  2391. isLoading=true;
  2392. document.body.appendChild(loadingDiv);
  2393. let sleep=ruleParser.curSiteRule.sleep||0;
  2394. setTimeout(()=>{
  2395. if(ruleParser.curSiteRule.pageElementByJs){
  2396. var over=ele=>{
  2397. loadPageOver();
  2398. if(ele){
  2399. createPageBar(nextLink);
  2400. ruleParser.insertPage(null, ele, nextLink, null, true);
  2401. if(autoLoadNum>=0){
  2402. if(autoLoadNum!=0 && --autoLoadNum==0){
  2403. autoLoadNum=-1;
  2404. }else{
  2405. nextPage();
  2406. }
  2407. }
  2408. }else{
  2409. debug("Stop as no page when get by js");
  2410. isPause=true;
  2411. }
  2412. };
  2413. try{
  2414. Function("over",'"use strict";' + ruleParser.curSiteRule.pageElementByJs)(over);
  2415. }catch(e){
  2416. debug(e);
  2417. }
  2418. }else if(ruleParser.curSiteRule.action==1 && !isJs){
  2419. requestFromIframe(nextLink, (doc, eles)=>{
  2420. loadPageOver();
  2421. if(eles){
  2422. createPageBar(nextLink);
  2423. ruleParser.insertPage(doc, eles, nextLink, null, true);
  2424. if(autoLoadNum>=0){
  2425. if(autoLoadNum!=0 && --autoLoadNum==0){
  2426. autoLoadNum=-1;
  2427. }else{
  2428. nextPage();
  2429. }
  2430. }
  2431. }
  2432. });
  2433. }else if((forceState==2||ruleParser.curSiteRule.action==2) && !isJs){
  2434. forceIframe(nextLink, (iframe, eles)=>{
  2435. loadPageOver();
  2436. let pageBar=createPageBar(nextLink);
  2437. iframe.parentNode.insertBefore(pageBar, iframe);
  2438. if(autoLoadNum>=0){
  2439. if(autoLoadNum!=0 && --autoLoadNum==0){
  2440. autoLoadNum=-1;
  2441. }else{
  2442. nextPage();
  2443. }
  2444. }
  2445. });
  2446. }else{
  2447. if(!isJs){
  2448. requestDoc(nextLink, (eles)=>{
  2449. loadPageOver();
  2450. if(eles){
  2451. createPageBar(nextLink);
  2452. if(autoLoadNum>=0){
  2453. if(autoLoadNum!=0 && --autoLoadNum==0){
  2454. autoLoadNum=-1;
  2455. }else{
  2456. nextPage();
  2457. }
  2458. }
  2459. }
  2460. });
  2461. }else{
  2462. emuPage((doc, eles)=>{
  2463. loadPageOver();
  2464. if(eles){
  2465. createPageBar(nextLink);
  2466. ruleParser.insertPage(doc, eles, "", null, true);
  2467. if(autoLoadNum>=0){
  2468. if(autoLoadNum!=0 && --autoLoadNum==0){
  2469. autoLoadNum=-1;
  2470. }else{
  2471. nextPage();
  2472. }
  2473. }
  2474. }
  2475. });
  2476. }
  2477. }
  2478. },sleep);
  2479. }
  2480. }
  2481.  
  2482. function init(){
  2483. initRules(()=>{
  2484. initPage();
  2485. });
  2486. }
  2487. setTimeout(()=>{
  2488. init();
  2489. },300);
  2490. })();

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址