东方永页机

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

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

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