东方永页机

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

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

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