东方永页机

自动翻页脚本 - 自动加载并拼接下一分页内容,无需规则驱动支持任意网页

目前为 2022-05-27 提交的版本,查看 最新版本

  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.7.6
  14. // @description Perpetual pages - Most powerful Auto Pager script. Auto loading next paginated web pages and inserting into current page.
  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. // @match *://*/*
  26. // @license MIT
  27. // @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==
  28. // @grant GM_xmlhttpRequest
  29. // @grant GM_registerMenuCommand
  30. // @grant GM_notification
  31. // @grant GM_getValue
  32. // @grant GM_setValue
  33. // @grant GM_addStyle
  34. // @grant GM_openInTab
  35. // @grant GM_deleteValue
  36. // @grant GM.xmlHttpRequest
  37. // @grant GM.registerMenuCommand
  38. // @grant GM.notification
  39. // @grant GM.getValue
  40. // @grant GM.setValue
  41. // @grant GM.addStyle
  42. // @grant GM.openInTab
  43. // @grant GM.deleteValue
  44. // @supportURL https://github.com/hoothin/UserScripts/issues
  45. // @connect wedata.net
  46. // @connect githubusercontent.com
  47. // @run-at document-idle
  48. // @exclude http://www.toodledo.com/tasks/*
  49. // @exclude http*://maps.google.com*/*
  50. // @exclude *://www.google.*/_/chrome/newtab*
  51. // @exclude *://mega.*/*
  52. // @exclude *://*.mega.*/*
  53. // @exclude *://*.youku.com/v_*
  54. // @exclude *://*pan.baidu.com
  55. // @exclude *://*.iqiyi.com/v_*
  56. // @exclude *://*.iqiyi.com/w_*
  57. // @exclude *://*.iqiyi.com/a_*
  58. // @exclude *://*.le.com/ptv/vplay/*
  59. // @exclude *://v.qq.com/x/cover/*
  60. // @exclude *://v.qq.com/x/page/*
  61. // @exclude *://v.qq.com/tv/*
  62. // @exclude *://*.tudou.com/listplay/*
  63. // @exclude *://*.tudou.com/albumplay/*
  64. // @exclude *://*.tudou.com/programs/view/*
  65. // @exclude *://*.mgtv.com/b/*
  66. // @exclude *://film.sohu.com/album/*
  67. // @exclude *://tv.sohu.com/v/*
  68. // @exclude *://*.bilibili.com/video/*
  69. // @exclude *://*.bilibili.com/bangumi/play/*
  70. // @exclude *://*.baofeng.com/play/*
  71. // @exclude *://vip.pptv.com/show/*
  72. // @exclude *://v.pptv.com/show/*
  73. // @exclude *://www.le.com/ptv/vplay/*
  74. // @exclude *://www.wasu.cn/Play/show/*
  75. // @exclude *://m.v.qq.com/*
  76. // @exclude *://m.iqiyi.com/*
  77. // @exclude *://m.youku.com/alipay_video/*
  78. // @exclude *://m.mgtv.com/b/*
  79. // @exclude *://m.tv.sohu.com/v/*
  80. // @exclude *://m.film.sohu.com/album/*
  81. // @exclude *://m.le.com/ptv/vplay/*
  82. // @exclude *://m.pptv.com/show/*
  83. // @exclude *://m.acfun.cn/v/*
  84. // @exclude *://m.bilibili.com/video/*
  85. // @exclude *://m.bilibili.com/anime/*
  86. // @exclude *://m.bilibili.com/bangumi/play/*
  87. // @exclude *://m.wasu.cn/Play/show/*
  88. // @exclude *://www.youtube.com
  89. // @exclude *://www.youtube.com/
  90. // @exclude *://www.youtube.com/watch*
  91. // @exclude *://baike.baidu.com/*
  92. // @exclude *://*.instagram.com/*
  93. // @exclude *://order.jd.com/*
  94. // @exclude *://pagetual.hoothin.com/*
  95. // @exclude *://hoothin.github.io/PagetualGuide/*
  96. // @exclude *://wenku.baidu.com/view/*
  97. // @connect *
  98. // ==/UserScript==
  99.  
  100. (function() {
  101. 'use strict';
  102.  
  103. if (window.name === 'pagetual-iframe' || (window.frameElement && window.frameElement.name === 'pagetual-iframe')) {
  104. var domloaded = function (){
  105. window.scroll(window.scrollX, 999999);
  106. window.parent.postMessage('pagetual-iframe:DOMLoaded', '*');
  107. };
  108. if(window.opera){
  109. document.addEventListener('DOMContentLoaded', domloaded, false);
  110. } else {
  111. domloaded();
  112. }
  113. return;
  114. }
  115.  
  116. if(window.top != window.self){
  117. try{
  118. if (top.location.hostname != window.location.hostname || window.top != window.parent) {
  119. return;
  120. }
  121. }catch(e){
  122. return;
  123. }
  124. }
  125.  
  126. const lang = navigator.appName=="Netscape"?navigator.language:navigator.userLanguage;
  127. let config={};
  128. switch (lang){
  129. case "zh-CN":
  130. case "zh-SG":
  131. config={
  132. enableDebug:"调试模式,输出信息至控制台",
  133. disable:"暂时禁用",
  134. disableSite:"在此站禁用",
  135. enable:"启用翻页",
  136. toTop:"回到顶部",
  137. toBottom:"前往页尾",
  138. current:"当前页",
  139. forceIframe:"强制拼接",
  140. cancelForceIframe:"取消强制拼接",
  141. configure:"打开配置页",
  142. firstUpdate:"点击此处初始化规则",
  143. update:"更新规则",
  144. click2update:"点击立即更新规则",
  145. loadNow:"立即翻页",
  146. loadConfirm:"要翻几页?(0为不间断)",
  147. noNext:"没有找到下一页,请新建规则",
  148. passSec:"更新于 #t# 秒前",
  149. passMin:"更新于 #t# 分钟前",
  150. passHour:"更新于 #t# 小时前",
  151. passDay:"更新于 #t# 天前",
  152. cantDel:"无法删除内置规则",
  153. confirmDel:"是否确认要删除此规则?",
  154. updateSucc:"更新成功",
  155. beginUpdate:"正在更新,请稍候",
  156. customUrls:"导入规则url,一行一条,AutoPagerize 格式规则需要以\"0|\"开头",
  157. customRules:"输入【东方永页机】格式的自定义规则",
  158. save:"保存设置",
  159. loadingText:"少女祈祷中...",
  160. opacity:"分页隔条不透明值",
  161. hideBar:"空白处双击隐藏分页隔条",
  162. dbClick2Stop:"空白处双击暂停翻页",
  163. sortTitle:"排序在下次更新规则后生效",
  164. autoRun:"自动启用,否则为白名单模式",
  165. inputPageNum:"输入页码跳转",
  166. enableHistory:"翻页后写入历史记录",
  167. initRun:"打开页面后立即尝试翻页,否则滚动至页尾再翻页",
  168. preload:"翻页前预读下一页,加速浏览",
  169. click2ImportRule:"点击下方添加特殊规则库,添加后再行更新:",
  170. forceAllBody:"是否拼接整个页面?",
  171. openInNewTab:"使拼接页面的内容在新页面打开",
  172. importSucc:"导入成功",
  173. editCurrent:"自定义此站规则",
  174. editBlacklist:"编辑黑名单网址,一行一条,支持? *通配符",
  175. upBtnImg:"回到页首图标",
  176. downBtnImg:"前往页尾图标"
  177. };
  178. break;
  179. case "zh-TW":
  180. case "zh-HK":
  181. config={
  182. enableDebug:"調試模式,輸出信息至控制台",
  183. disable:"暫時禁用",
  184. disableSite:"在此站禁用",
  185. enable:"啟用翻頁",
  186. toTop:"回到頂部",
  187. toBottom:"前往頁尾",
  188. current:"當前頁",
  189. forceIframe:"強制拼接",
  190. cancelForceIframe:"取消强制拼接",
  191. configure:"打開配置頁",
  192. firstUpdate:"點擊此處初始化規則",
  193. update:"更新規則",
  194. click2update:"點擊立即更新規則",
  195. loadNow:"立即翻頁",
  196. loadConfirm:"要翻几頁?(0為不間斷)",
  197. noNext:"沒有找到下一頁,請新建規則",
  198. passSec:"更新于 #t# 秒前",
  199. passMin:"更新于 #t# 分鐘前",
  200. passHour:"更新于 #t# 小時前",
  201. passDay:"更新于 #t# 天前",
  202. cantDel:"無法刪除内置規則",
  203. confirmDel:"是否確認要刪除此規則?",
  204. updateSucc:"更新成功",
  205. beginUpdate:"正在更新,請稍候",
  206. customUrls:"導入規則url,一行一條,AutoPagerize 格式規則需要以\"0|\"開頭",
  207. customRules:"輸入【東方永頁機】格式的自定義規則",
  208. save:"存儲設置",
  209. loadingText:"少女祈禱中...",
  210. opacity:"分頁隔條不透明值",
  211. hideBar:"空白處雙擊隱藏分頁隔條",
  212. dbClick2Stop:"空白處雙擊暫停翻頁",
  213. sortTitle:"排序在下次更新規則後生效",
  214. autoRun:"自動啓用,否則為白名單模式",
  215. inputPageNum:"輸入頁碼跳轉",
  216. enableHistory:"翻頁后寫入歷史記錄",
  217. initRun:"打開頁面后立即嘗試翻頁,否則滾動至頁尾再翻頁",
  218. preload:"翻頁前預讀下一頁,加速瀏覽",
  219. click2ImportRule:"點擊下方添加特殊規則庫,添加後再行更新:",
  220. forceAllBody:"是否拼接整個頁面?",
  221. openInNewTab:"使拼接頁面的内容在新頁面打開",
  222. importSucc:"導入成功",
  223. editCurrent:"自定義此站規則",
  224. editBlacklist:"編輯黑名單網址,一行一條,支持? *通配符",
  225. upBtnImg:"回到頁首圖標",
  226. downBtnImg:"前往頁尾圖標"
  227. };
  228. break;
  229. case "ja":
  230. config = {
  231. enableDebug:"デバッグモード",
  232. disable: "一時的に無効にする",
  233. disableSite:"このサイト無効",
  234. enable: "ページめくりを有効にする",
  235. toTop: "トップに戻る",
  236. toBottom: "ページの下部に移動",
  237. current: "現在のページ",
  238. forceIframe: "強制ステッチ",
  239. cancelForceIframe: "強制ステッチをキャンセル",
  240. configure: "設定ページを開く",
  241. firstUpdate:"ここをクリックしてルールを初期化します",
  242. update: "更新ルール",
  243. click2update:"今すぐルールを更新してください",
  244. loadNow:"今すぐページをめくる",
  245. loadConfirm:"数ページめくりたいですか?(0は途切れない)",
  246. noNext:"次のページが見つかりません、新しいルールを作成してください",
  247. passSec: "#t#秒前に更新",
  248. passMin: "#t#分前に更新",
  249. passHour: "#t#時間前に更新",
  250. passDay: "#t#日前に更新",
  251. cantDel: "組み込みルールを削除できません",
  252. confirmDel: "このルールを削除してもよろしいですか?",
  253. updateSucc: "更新に成功しました",
  254. beginUpdate: "更新中、お待ちください",
  255. customUrls: "インポートルールのURL、1行に1つ、AutoPagerizeフォーマットルールは\"0|\"で始まる必要があります",
  256. customRules: "【東方永頁機】の形式でカスタムルールを入力してください",
  257. save: "設定を保存",
  258. loadingText: "少女祈祷中...",
  259. opacity:"ページネーションバーの不透明値",
  260. hideBar:"空白部分をダブルクリックして、ページ区切り文字を非表示にします",
  261. dbClick2Stop:"空白部分をダブルクリックしてページめくりを一時停止します",
  262. sortTitle:"並べ替えは、次のルールの更新後に有効になります",
  263. autoRun:"自動的に有効",
  264. inputPageNum:"ジャンプするページ番号を入力",
  265. enableHistory:"ページめくり後の履歴を書く",
  266. initRun:"Webページを開いた直後にページをめくる",
  267. preload:"事前に次のページを読む",
  268. click2ImportRule:"以下をクリックして、ルールベースを追加します:",
  269. forceAllBody:"フルページ埋め込み?",
  270. openInNewTab:"スプライスされたページのコンテンツを新しいページで開きます",
  271. importSucc:"インポート完了",
  272. editCurrent:"現在のルールの編集",
  273. editBlacklist:"ブラックリストのURLを編集し、1行ずつ、サポート? *ワイルドカード",
  274. upBtnImg:"トップアイコンに戻る",
  275. downBtnImg:"フッターアイコンに移動"
  276. };
  277. break;
  278. default:
  279. config={
  280. enableDebug:"Enable debug output",
  281. disable:"Disable",
  282. disableSite:"Disable on the site",
  283. enable:"Enable",
  284. toTop:"To Top",
  285. toBottom:"To Bottom",
  286. current:"Current Page",
  287. forceIframe:"Force to join",
  288. cancelForceIframe:"Cancel Force join",
  289. configure:"Configure",
  290. firstUpdate:"Click here to initialize the rules",
  291. update:"Update rules",
  292. click2update:"Click to update rules from url now",
  293. loadNow:"Load next now",
  294. loadConfirm:"How much pages do you want to load? (0 means infinite)",
  295. noNext:"No next link found, please create a new rule",
  296. passSec:"Updated #t# seconds ago",
  297. passMin:"Updated #t# minutes ago",
  298. passHour:"Updated #t# hours ago",
  299. passDay:"Updated #t# days ago",
  300. cantDel:"Can't delete buildin rules",
  301. confirmDel:"Are you sure you want to delete this rule?",
  302. updateSucc:"Update succeeded",
  303. beginUpdate:"Begin update, wait a minute please",
  304. customUrls:"Import rule url, One url per line, rules on AutoPagerize format need to start with \"0|\"",
  305. customRules:"Input custom rules with [Pagetual] format",
  306. save:"Save",
  307. loadingText:"Shojo Now Loading...",
  308. opacity:"Pagination spacer opacity",
  309. hideBar:"Double-click on the blank space to hide the paging spacer",
  310. dbClick2Stop:"Double-click on the blank space to pause",
  311. sortTitle:"Sorting takes effect after the next rule update",
  312. autoRun:"Auto run (black list mode)",
  313. inputPageNum:"Enter page number to jump",
  314. enableHistory:"Write history after page turning",
  315. initRun:"Turn pages immediately after opening",
  316. preload:"Preload next page for speeding up",
  317. click2ImportRule:"Click to import base rules link, then click to update rules:",
  318. forceAllBody:"Join full body of page?",
  319. openInNewTab:"Open urls of additions in new tab",
  320. importSucc:"Import completed",
  321. editCurrent:"Edit rule for current",
  322. editBlacklist:"Edit the blacklist urls, line by line, Support ? * for wildcard",
  323. upBtnImg:"Icon of back to top",
  324. downBtnImg:"Icon of go to footer"
  325. };
  326. break;
  327. }
  328. var i18n=(name, param)=>{
  329. return config[name]?config[name].replace("#t#",param):name;
  330. };
  331.  
  332. var noRuleTest=false;
  333. var enableDebug=true;
  334. var debug=str=>{
  335. if(enableDebug){
  336. console.debug(str);
  337. }
  338. };
  339.  
  340. var _GM_xmlhttpRequest,_GM_registerMenuCommand,_GM_notification,_GM_addStyle,_GM_openInTab;
  341. if(typeof GM_xmlhttpRequest!='undefined'){
  342. _GM_xmlhttpRequest=GM_xmlhttpRequest;
  343. }else if(typeof GM!='undefined' && typeof GM.xmlHttpRequest!='undefined'){
  344. _GM_xmlhttpRequest=GM.xmlHttpRequest;
  345. }else{
  346. _GM_xmlhttpRequest=(f)=>{fetch(f.url).then(response=>response.text()).then(data=>{let res={response:data};f.onload(res)}).catch(f.onerror())};
  347. }
  348. if(typeof GM_registerMenuCommand!='undefined'){
  349. _GM_registerMenuCommand=GM_registerMenuCommand;
  350. }else if(typeof GM!='undefined' && typeof GM.registerMenuCommand!='undefined'){
  351. _GM_registerMenuCommand=GM.registerMenuCommand;
  352. }else{
  353. _GM_registerMenuCommand=(s,f)=>{};
  354. }
  355. if(typeof GM_notification!='undefined'){
  356. _GM_notification=GM_notification;
  357. }else if(typeof GM!='undefined' && typeof GM.notification!='undefined'){
  358. _GM_notification=GM.notification;
  359. }else{
  360. _GM_notification=(s)=>{showTips(s)};
  361. }
  362. if(typeof GM_openInTab!='undefined'){
  363. _GM_openInTab=GM_openInTab;
  364. }else if(typeof GM!='undefined' && typeof GM.openInTab!='undefined'){
  365. _GM_openInTab=GM.openInTab;
  366. }else{
  367. _GM_openInTab=(s,t)=>{window.open(s)};
  368. }
  369. if(typeof GM_addStyle!='undefined'){
  370. _GM_addStyle=GM_addStyle;
  371. }else if(typeof GM!='undefined' && typeof GM.addStyle!='undefined'){
  372. _GM_addStyle=GM.addStyle;
  373. }else{
  374. _GM_addStyle=cssStr=>{
  375. let styleEle=document.createElement("style");
  376. styleEle.innerHTML=cssStr;
  377. document.head.appendChild(styleEle);
  378. };
  379. }
  380. var _unsafeWindow=(typeof unsafeWindow=='undefined')?window:unsafeWindow;//兼容 ios userscripts 的寫法
  381. var storage={
  382. supportGM: typeof GM_getValue=='function' && typeof GM_getValue('a','b')!='undefined',
  383. supportGMPromise: typeof GM!='undefined' && typeof GM.getValue=='function' && typeof GM.getValue('a','b')!='undefined',
  384. mxAppStorage:(function(){
  385. try{
  386. return window.external.mxGetRuntime().storage;
  387. }catch(e){
  388. }
  389. })(),
  390. operaUJSStorage:(function(){
  391. try{
  392. return window.opera.scriptStorage;
  393. }catch(e){
  394. }
  395. })(),
  396. setItem:function(key,value){
  397. if(this.operaUJSStorage){
  398. this.operaUJSStorage.setItem(key,value);
  399. }else if(this.mxAppStorage){
  400. this.mxAppStorage.setConfig(key,value);
  401. }else if(this.supportGM){
  402. GM_setValue(key,value);
  403. if(value==="" && typeof GM_deleteValue!='undefined'){
  404. GM_deleteValue(key);
  405. }
  406. }else if(this.supportGMPromise){
  407. GM.setValue(key,value);
  408. if(value==="" && typeof GM!='undefined' && typeof GM.deleteValue!='undefined'){
  409. GM.deleteValue(key);
  410. }
  411. }else if(window.localStorage){
  412. window.localStorage.setItem(key,value);
  413. }
  414. },
  415. getItem:function(key,cb){
  416. var value;
  417. if(this.operaUJSStorage){
  418. value=this.operaUJSStorage.getItem(key);
  419. }else if(this.mxAppStorage){
  420. value=this.mxAppStorage.getConfig(key);
  421. }else if(this.supportGM){
  422. value=GM_getValue(key);
  423. }else if(this.supportGMPromise){
  424. value=GM.getValue(key).then(v=>{cb(v)});
  425. return;
  426. }else if(window.localStorage){
  427. value=window.localStorage.getItem(key);
  428. };
  429. cb(value);
  430. }
  431. };
  432. var rulesData={},ruleUrls,updateDate,configPage="https://github.com/hoothin/UserScripts/tree/master/Pagetual";
  433. var ruleImportUrlReg=/greasyfork\.org\/.*scripts\/438684[^\/]*(\/discussions|\/?$)|github\.com\/hoothin\/UserScripts\/(tree\/master\/Pagetual|issues)/i;
  434. var allOfBody="body>*";
  435. _GM_registerMenuCommand(i18n("configure"), ()=>{
  436. _GM_openInTab(configPage,{active:true});
  437. });
  438. _GM_registerMenuCommand(i18n("editCurrent"), ()=>{
  439. let editTemp;
  440. if(ruleParser.curSiteRule.url && !ruleParser.curSiteRule.singleUrl){
  441. editTemp=ruleParser.curSiteRule;
  442. }else{
  443. editTemp={
  444. name: document.title,
  445. url: "^"+location.origin.replace(/\./g,"\\."),
  446. pageElement: ruleParser.curSiteRule.pageElement||""
  447. };
  448. }
  449. rulesData.editTemp=editTemp;
  450. storage.setItem("rulesData", rulesData);
  451. _GM_openInTab(configPage,{active:true});
  452. });
  453.  
  454. function getElementByXpath(xpath, contextNode, doc){
  455. doc = doc || document;
  456. contextNode = contextNode || doc;
  457. try {
  458. var result = doc.evaluate(xpath, contextNode, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
  459. return result.singleNodeValue && result.singleNodeValue.nodeType === 1 && result.singleNodeValue;
  460. } catch (err) {
  461. throw new Error(`Invalid xpath: ${xpath}`);
  462. }
  463. }
  464.  
  465. function getAllElementsByXpath(xpath, contextNode, doc){
  466. doc = doc || document;
  467. contextNode = contextNode || doc;
  468. var result = [];
  469. try {
  470. var query = doc.evaluate(xpath, contextNode, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  471. for (var i = 0; i < query.snapshotLength; i++) {
  472. var node = query.snapshotItem(i);
  473. if (node.nodeType === 1) result.push(node);
  474. }
  475. } catch (err) {
  476. throw new Error(`Invalid xpath: ${xpath}`);
  477. }
  478. return result;
  479. }
  480.  
  481. class RuleParser {
  482. constructor() {
  483. this.hpRules=[];
  484. this.customRules=[];
  485. this.rules=[];
  486. this.pageDoc=document;
  487. this.nextLinkHref=null;
  488. this.nextTitle="";
  489. this.oldUrl="";
  490. this.curUrl=location.href;
  491. this.curSiteRule={};
  492. }
  493.  
  494. initSavedRules(callback){
  495. var self=this;
  496. storage.getItem("hpRules", hpRules=>{
  497. if(hpRules)self.hpRules=hpRules;
  498. storage.getItem("customRules", customRules=>{
  499. if(customRules)self.customRules=customRules;
  500. storage.getItem("rules", rules=>{
  501. if(rules)self.rules=rules;
  502. callback();
  503. });
  504. });
  505. });
  506. }
  507.  
  508. saveCurSiteRule(){
  509. if(!this.curSiteRule || !this.curSiteRule.url || this.curSiteRule.singleUrl)return;
  510. this.hpRules=this.hpRules.filter(item=>{return item&&item.url!=this.curSiteRule.url});
  511. this.hpRules.unshift(this.curSiteRule);
  512. if(this.hpRules.length>30){
  513. this.hpRules.pop();
  514. }
  515. storage.setItem("hpRules", this.hpRules);
  516. }
  517.  
  518. requestJSON(url, callback){
  519. _GM_xmlhttpRequest({
  520. url: url,
  521. method: 'GET',
  522. timeout: 20000,
  523. onload: function(res) {
  524. let json=null;
  525. try{
  526. json=JSON.parse(res.response||res.responseText);
  527. }catch(e){
  528. debug(e);
  529. }
  530. callback(json);
  531. },
  532. onerror: function(e) {
  533. callback(null, e);
  534. },
  535. ontimeout: function(e) {
  536. callback(null, e);
  537. }
  538. });
  539. }
  540.  
  541. formatRule(item, type, from){
  542. switch(type){
  543. case 0:
  544. return {
  545. from:from,
  546. type:type,
  547. name:item.name,
  548. action:item.data.forceIframe=="true"?1:0,
  549. url:item.data.url,
  550. pageElement:item.data.pageElement,
  551. nextLink:item.data.nextLink,
  552. insert:item.data.insertBefore,
  553. insertPos:1,
  554. updatedAt:item.data.updated_at,
  555. css:item.data.Stylus+item.data.CSS,
  556. pageAction:item.data.bookmarklet
  557. };
  558. break;
  559. case 1:
  560. default:
  561. item.from=from;
  562. if(typeof(item.type) == "undefined")item.type=type;
  563. return item;
  564. break;
  565. }
  566. return null;
  567. }
  568.  
  569. addRuleByUrl(url, type, from, callback) {
  570. if(url.indexOf("?")==-1){
  571. url=url+"?"+Date.now();
  572. }else{
  573. url=url+"&"+Date.now();
  574. }
  575. this.requestJSON(url, (json,err)=>{
  576. if(!json){
  577. debug("Update "+url+" rules fail!");
  578. debug(err);
  579. }
  580. this.addRules(json, type, from);
  581. callback(json, err);
  582. });
  583. }
  584.  
  585. addRules(rules, type, from) {
  586. if(rules && rules.length>0){
  587. this.rules=this.rules.filter(item=>{return item.from!=from});
  588. rules.forEach(item=>{
  589. let rule=this.formatRule(item, type, from);
  590. if(rule){
  591. this.rules.unshift(rule);
  592. }
  593. });
  594. }
  595. }
  596.  
  597. getRule(callback) {
  598. if(noRuleTest){
  599. this.curSiteRule={};
  600. this.curSiteRule.url=location.origin+location.pathname;
  601. this.curSiteRule.singleUrl=true;
  602. callback();
  603. return;
  604. }
  605. if(this.curSiteRule && this.curSiteRule.url){
  606. return this.curSiteRule;
  607. }
  608. var self=this;
  609.  
  610. function setRule(r){
  611. self.curSiteRule=r;
  612. debug(r);
  613. callback();
  614. }
  615.  
  616. function ruleMatch(r){
  617. let pageElement,nextLink,insert;
  618. if(r.nextLink && r.nextLink!="0" && r.nextLink!=0){
  619. nextLink=r.type==0?getElementByXpath(r.nextLink):document.querySelector(r.nextLink);
  620. if(!nextLink)return false;
  621. }
  622. if(r.pageElement){
  623. pageElement=r.type==0?getElementByXpath(r.pageElement):document.querySelector(r.pageElement);
  624. if(!pageElement)return false;
  625. }
  626. if(r.insert){
  627. insert=r.type==0?getElementByXpath(r.insert):document.querySelector(r.insert);
  628. if(!insert)return false;
  629. }
  630. return true;
  631. }
  632.  
  633. function checkRule(r){
  634. let urlReg=new RegExp(r.url, "i");
  635. if(urlReg.test(location.href)){
  636. if(r.wait){
  637. let waitTime=500,checkEval;
  638. if(isNaN(r.wait)){
  639. try{
  640. checkEval=Function("doc",'"use strict";' + r.wait);
  641. }catch(e){
  642. debug(e);
  643. }
  644. }else{
  645. waitTime=r.wait;
  646. }
  647. let checkReady=()=>{
  648. setTimeout(()=>{
  649. if(!ruleMatch(r) || (checkEval && !checkEval(document))){
  650. checkReady();
  651. }else{
  652. setRule(r);
  653. }
  654. },parseInt(waitTime));
  655. };
  656. checkReady();
  657. return true;
  658. }
  659. if(r.pinUrl){
  660. setRule(r);
  661. return true;
  662. }
  663. if(!ruleMatch(r)){
  664. return false;
  665. }
  666. setRule(r);
  667. return true;
  668. }
  669. return false;
  670. }
  671.  
  672. for(let i in this.hpRules){
  673. let rule=this.hpRules[i];
  674. if(!rule || !rule.url)continue;
  675. if(rule.singleUrl){
  676. if(location.origin+location.pathname==rule.url){
  677. setRule(rule);
  678. return;
  679. }
  680. continue;
  681. }
  682. if(checkRule(rule))return;
  683. }
  684. for(let i in this.customRules){
  685. let rule=this.customRules[i];
  686. if(!rule || !rule.url)continue;
  687. if(checkRule(rule))return;
  688. }
  689. let r=0;
  690. function searchByTime(){
  691. setTimeout(()=>{
  692. let end=r+50;
  693. end=end>self.rules.length?self.rules.length:end;
  694. for(;r<end;r++){
  695. let rule=self.rules[r];
  696. if(checkRule(rule))return;
  697. }
  698. if(end>=self.rules.length){
  699. self.curSiteRule={};
  700. self.curSiteRule.url=location.origin+location.pathname;
  701. self.curSiteRule.singleUrl=true;
  702. callback();
  703. return;
  704. }else{
  705. searchByTime();
  706. }
  707. },10);
  708. }
  709. searchByTime();
  710. }
  711.  
  712. geneSelector(ele){
  713. let selector=ele.tagName;
  714. //Google id class都是隨機。百度更過分,style script順序都是隨機的
  715. //if(ele.id) selector += '#' + ele.id;
  716. //if(ele.classList) selector += [].map.call(ele.classList,d=>'.'+d).join('');
  717. if(ele.tagName!="HTML" && ele.tagName!="BODY"){
  718. if(ele.className) selector += [].map.call(ele.classList,d=>'.'+d).join('');
  719. let parent = ele.parentElement;
  720. if(parent){
  721. selector = this.geneSelector(parent) + ' > ' + selector;
  722. if(!ele.className){
  723. let i,j=0;
  724. for(i=0;i<parent.children.length;i++){
  725. if(parent.children[i].tagName==ele.tagName){
  726. j++;
  727. if(parent.children[i]==ele){
  728. break;
  729. }
  730. }
  731. }
  732. selector += (parent.tagName=="HTML"?"":`:nth-of-type(${j})`);
  733. }
  734. }
  735. }
  736. return selector;
  737. }
  738.  
  739. getPageElement(doc, curWin, dontFind) {
  740. let pageElement=null;
  741. let self=this;
  742. let body=doc.body;
  743. if(this.curSiteRule.pageElement){
  744. pageElement=this.curSiteRule.type==0?getAllElementsByXpath(this.curSiteRule.pageElement,doc,doc):doc.querySelectorAll(this.curSiteRule.pageElement);
  745. }else if(!this.curSiteRule.singleUrl && this.curSiteRule.type==0){
  746. pageElement=[body];
  747. }
  748. if(this.curSiteRule.singleUrl && pageElement && pageElement.length>0 && pageElement[0].tagName=="TR"){
  749. let mainTr=this.insert.previousElementSibling,mainTdNum=0,newTdNum=0;
  750. [].forEach.call(mainTr.children, el=>{
  751. if(el.tagName=="TD" || el.tagName=="TH"){
  752. mainTdNum+=el.colSpan||1;
  753. }
  754. });
  755. [].forEach.call(pageElement[0].children, el=>{
  756. if(el.tagName=="TD" || el.tagName=="TH"){
  757. newTdNum+=el.colSpan||1;
  758. }
  759. });
  760. if(mainTdNum!=newTdNum){
  761. this.curSiteRule.pageElement=allOfBody;
  762. pageElement=[body];
  763. this.getInsert(true);
  764. }
  765. }
  766. if((this.curSiteRule.singleUrl || !this.curSiteRule.pageElement) && (!pageElement || pageElement.length==0) && curWin && !dontFind){
  767. if(!body)return null;
  768. let bodyHeight=parseInt(body.scrollHeight);
  769. let curHeight=bodyHeight;
  770. let windowHeight=window.innerHeight || document.documentElement.clientHeight;
  771. let needCheckNext=(doc==document && this.initNext);
  772. function checkElement(ele){
  773. if(ele.childNodes && ele.childNodes.length==1)ele=ele.childNodes[0];
  774. if(ele.tagName=="PICTURE"){
  775. self.curSiteRule.pageElement=self.geneSelector(ele.parentNode)+">"+ele.tagName;
  776. debug(self.curSiteRule.pageElement);
  777. return [ele];
  778. }
  779. if(curHeight/bodyHeight<=0.25){
  780. self.curSiteRule.pageElement=allOfBody;
  781. debug(self.curSiteRule.pageElement);
  782. return [body];
  783. }
  784. if(ele.tagName=="FORM"){
  785. self.curSiteRule.pageElement=self.geneSelector(ele)+">*";
  786. debug(self.curSiteRule.pageElement);
  787. return ele.children;
  788. }
  789. if(ele.children.length==0 && !self.curSiteRule.pageElement){
  790. if(ele.parentNode.tagName=="P")ele=ele.parentNode;
  791. self.curSiteRule.pageElement=self.geneSelector(ele.parentNode)+">"+ele.tagName;
  792. debug(self.curSiteRule.pageElement);
  793. return [ele];
  794. }
  795. let i,maxHeight=curHeight*0.55,curMaxEle=null,curMaxArea=0,maxWidth=0;
  796. let isHori=true;
  797. let offsetTop=ele.children[0].offsetTop;
  798. for(i=1;i<ele.children.length;i++){
  799. if(ele.children[i].offsetTop!=offsetTop){
  800. isHori=false;
  801. break;
  802. }
  803. }
  804. for(i=0;i<ele.children.length;i++){
  805. let curNode=ele.children[i];
  806. if(curNode.tagName=="CANVAS")continue;
  807. if(curNode.tagName!="IMG" && /^\s*$/.test(curNode.innerText))continue;
  808. if(needCheckNext && !curNode.contains(self.initNext) && getElementTop(curNode)>windowHeight){
  809. continue;
  810. }
  811. let comStyle=curWin.getComputedStyle(curNode);
  812. let h=parseInt(curNode.scrollHeight);
  813. let w=parseInt(curNode.scrollWidth);
  814. if(isNaN(h) || isNaN(w))continue;
  815. if(isHori && h==0)continue;
  816. let a=h*w+h,moreChild=curNode.children[0];
  817. while(moreChild){
  818. comStyle=curWin.getComputedStyle(moreChild);
  819. let ch=parseInt(moreChild.scrollHeight);
  820. let cw=parseInt(moreChild.scrollWidth);
  821. if(h<ch)h=ch;
  822. if(moreChild.innerText!="" && !isNaN(ch) && !isNaN(cw)){
  823. a+=ch*cw;
  824. }
  825. moreChild=moreChild.nextElementSibling;
  826. }
  827. let isMax=false;
  828. if(isHori){
  829. if(maxWidth<w){
  830. isMax=true;
  831. }else if(maxWidth==w && curMaxArea<a){
  832. isMax=true;
  833. }
  834. }else{
  835. isMax=curMaxArea<a;
  836. }
  837. if(curMaxEle==null || isMax){
  838. if(h>0 || !isHori)curHeight=h;
  839. curMaxArea=a;
  840. maxWidth=w;
  841. curMaxEle=curNode;
  842. }
  843. }
  844. if(curMaxEle && (isHori || curHeight>maxHeight || (needCheckNext && curHeight>windowHeight && ele.contains(self.initNext)))){
  845. return checkElement(curMaxEle);
  846. }
  847. if(ele.tagName=="P" || ele.tagName=="BR")ele=ele.parentNode;
  848. if(ele.tagName=="TBODY"){
  849. self.curSiteRule.pageElement=self.geneSelector(ele)+">*";
  850. if(ele.children.length>0 && ele.children[0].querySelector("th")){
  851. self.curSiteRule.pageElement+=":not(:first-child)";
  852. }
  853. debug(self.curSiteRule.pageElement);
  854. return ele.children;
  855. }
  856. self.curSiteRule.pageElement=self.geneSelector(ele);
  857. if(ele.children.length>1){
  858. let middleChild=ele.children[parseInt(ele.children.length/2)];
  859. if((middleChild.style && middleChild.style.position=="absolute" && middleChild.style.left && middleChild.style.top) || ele.tagName=="UL" || curHeight==0){
  860. ele=[ele];
  861. }else{
  862. self.curSiteRule.pageElement+=">*";
  863. ele=ele.children;
  864. }
  865. }else{
  866. ele=[ele];
  867. }
  868. debug(self.curSiteRule.pageElement);
  869. return ele;
  870. }
  871. pageElement=checkElement(body);
  872. if(pageElement)this.saveCurSiteRule();
  873. }
  874. return pageElement;
  875. }
  876.  
  877. getPage(doc){
  878. if(_unsafeWindow.Discourse)return {};
  879. let canSave=false;//發現頁碼選擇器在其他頁對不上,還是別保存了
  880. let url=this.curUrl.replace("#!","").replace("index.php?","?");
  881. let pageNum=1,preStr="",afterStr="";
  882. let pageMatch1=url.match(/(.*[a-z\/\-_](?:p|page)?\/?)(\d+)(\.s?html?$|\/?$)/i);
  883. let pageMatch2=url.match(/(.*[\?&]p(?:age)?=)(\d+)($|[#&].*)/i);
  884. if(pageMatch1){
  885. preStr=pageMatch1[1];
  886. pageNum=parseInt(pageMatch1[2]);
  887. afterStr=pageMatch1[3];
  888. }else if(pageMatch2){
  889. preStr=pageMatch2[1];
  890. pageNum=parseInt(pageMatch2[2]);
  891. afterStr=pageMatch2[3];
  892. }
  893. let curPage=doc,i,cur,jsNext;
  894. let next1,next2,next3,next4,nextJs1,nextJs2,nextJs3;
  895. let next=curPage.querySelector(".page-next>a")||
  896. curPage.querySelector("a.next_page")||
  897. curPage.querySelector("#next_page")||
  898. curPage.querySelector(".nextPage")||
  899. curPage.querySelector("a[data-pagination=next]")||
  900. curPage.querySelector("ul.pagination>li.active+li>a")||
  901. curPage.querySelector(".pagination a[rel=next]")||
  902. curPage.querySelector(".pagination-nav__item--next>a")||
  903. curPage.querySelector("a[title='Next page']")||
  904. curPage.querySelector("a.pageright")||
  905. curPage.querySelector("a#rightFix")||
  906. curPage.querySelector("a#next")||
  907. curPage.querySelector(".next>a")||
  908. curPage.querySelector(".next>button")||
  909. curPage.querySelector("a[alt=next]")||
  910. curPage.querySelector("button.next")||
  911. curPage.querySelector("[title=next]")||
  912. getElementByXpath("//a[contains(@class, 'page__next')]",curPage,curPage);
  913. if(!next){
  914. let nexts=curPage.querySelectorAll("a.next");
  915. for(i=0;i<nexts.length;i++){
  916. if(!/^([上前首尾][一1]?[页頁张張]|previous(\s*page)?\s*›?$|前のページ)/i.test(nexts[i].innerText.trim()) &&
  917. nexts[i].style.display!=="none" &&
  918. nexts[i].parentNode.style.display!=="none"){
  919. next=nexts[i];
  920. break;
  921. }
  922. }
  923. }
  924. if(next && (!next.href || /^javascript:/.test(next.href) || next.getAttribute("href")=="#")){
  925. jsNext=next;
  926. next=null;
  927. }
  928. if(!next){
  929. next=curPage.querySelectorAll("[aria-label='Next page']");
  930. if(next && next.length==1){
  931. next=next[0];
  932. if(!next.href || /^javascript:/.test(next.href) || next.getAttribute("href")=="#"){
  933. if(!jsNext)jsNext=next;
  934. next=null;
  935. }
  936. }else{
  937. next=null;
  938. }
  939. }
  940. if(!next){
  941. next=curPage.querySelectorAll("[aria-label='Next']");
  942. if(next && next.length==1){
  943. next=next[0];
  944. if(!next.href || /^javascript:/.test(next.href) || next.getAttribute("href")=="#"){
  945. if(!jsNext)jsNext=next;
  946. next=null;
  947. }
  948. }else{
  949. next=null;
  950. }
  951. }
  952. if(next && /^[下后後][一1]?[章话話篇]/i.test(next.innerText.trim())){
  953. next2=next;
  954. next=null;
  955. }
  956. if(!next){
  957. next=curPage.querySelector("a.curr");
  958. if(next){
  959. next=next.nextSibling;
  960. }
  961. }
  962. if(!next){
  963. next=curPage.querySelector("div.wp-pagenavi>span.current+a,div.page-nav>span.current+a,div.article-paging>span+a");
  964. }
  965. if(!next){
  966. let pageDiv=curPage.querySelector("div.pages>ul");
  967. if(pageDiv){
  968. cur=pageDiv.querySelector("li>b");
  969. if(cur)next=cur.parentNode.nextElementSibling;
  970. if(next)next=next.querySelector("a");
  971. }
  972. }
  973. if(!next){
  974. cur=curPage.querySelector(".number>ul>li.active");
  975. if(cur)next=cur.nextElementSibling;
  976. if(next)next=next.querySelector("a");
  977. }
  978. if(!next){
  979. let aTags=curPage.querySelectorAll("a,button");
  980. for(i=aTags.length-1;i>=0;i--){
  981. if(next1 && next2 && next3 && next4)break;
  982. let aTag=aTags[i];
  983. if(aTag.innerText=="§")continue;
  984. if(aTag.innerText.length>50)continue;
  985. if(aTag.style.display=="none")continue;
  986. if(aTag.href && /next$/i.test(aTag.href))continue;
  987. if(aTag.className && /slick|slide/i.test(aTag.className))continue;
  988. if(!next1){
  989. if(aTag.innerText.length>15)continue;
  990. if(/^[下后後][一1]?[页頁张張]|^next([ _-]?page)?\s*[›>→»]?$|次のページ|^次へ?$/i.test(aTag.innerText.trim())){
  991. if(!aTag.href || /^javascript:/.test(aTag.href) || aTag.getAttribute("href")=="#"){
  992. if(!nextJs1)nextJs1=aTag;
  993. }else{
  994. next1=aTag;
  995. }
  996. }
  997. }
  998. if(!next2){
  999. if(aTag.innerText.length>15)continue;
  1000. if(/^[下后後][一1]?[章话話篇]/i.test(aTag.innerText.trim()) || /nextpage/i.test(aTag.className)){
  1001. if(!aTag.href || /^javascript:/.test(aTag.href) || aTag.getAttribute("href")=="#"){
  1002. if(!nextJs2)nextJs2=aTag;
  1003. }else{
  1004. next2=aTag;
  1005. }
  1006. }
  1007. }
  1008. if(!next3){
  1009. if(aTag.innerText.length>15)continue;
  1010. if(aTag.innerText=="&gt;" || aTag.innerText=="▶" || aTag.innerText==">" || aTag.innerText=="›" || aTag.innerText=="→" || aTag.innerText=="»"){
  1011. if(!aTag.href || /^javascript:/.test(aTag.href) || aTag.getAttribute("href")=="#"){
  1012. if(!nextJs3)nextJs3=aTag;
  1013. }else{
  1014. next3=aTag;
  1015. }
  1016. }
  1017. }
  1018. if(!aTag.href || /^javascript:/.test(aTag.href) || aTag.getAttribute("href")=="#")continue;
  1019. if(!next4 && aTag.href.length<250){
  1020. let _aHref=aTag.href.replace("?&","?").replace("#!","").replace("index.php?","?");
  1021. let _aHrefTrim=_aHref;
  1022. if(preStr)_aHrefTrim=_aHrefTrim.replace(preStr,"");
  1023. if(afterStr)_aHrefTrim=_aHrefTrim.replace(afterStr,"");
  1024. if(pageNum<999 && _aHrefTrim==pageNum+1){
  1025. next4=aTag;
  1026. }else if(this.curUrl!=aTag.href){
  1027. let _url=url.replace(/\.s?html?$/i,"");
  1028. _aHref=_aHref.replace(/\.s?html?$/i,"");
  1029. if(_aHref.indexOf(_url)!=-1 && /^[\/\?&]?[_-]?(p|page)?=?\/?2(\/|\?|&|$)/i.test(_aHref.replace(_url,""))){
  1030. let curHref=aTag.getAttribute("href");
  1031. let pageOne=curHref.replace(/\/2(\/|\?|&|$)/,"/1$1");
  1032. if(pageOne==curHref)pageOne=null;
  1033. else pageOne=curPage.querySelector(`a[href='${pageOne}']`);
  1034. if(!pageOne || pageOne.className!=curHref.className)next4=aTag;
  1035. }
  1036. }
  1037. }
  1038. }
  1039. if(next3){
  1040. let eles=getAllElementsByXpath(`//a[text()='${next3.innerText}']`,curPage,curPage);
  1041. if(eles.length>1)next3=null;
  1042. }
  1043. }
  1044. if(!next)next=next1||next4||next3||next2||jsNext||nextJs1||nextJs3||nextJs2;
  1045. if(next && next.classList.contains("results-more"))next=null;
  1046. return {next:next,canSave:canSave};
  1047. }
  1048.  
  1049. canonicalUri(src) {
  1050. if(src.charAt(0)=="#")return location.href+src;
  1051. var root_page = /^[^?#]*\//.exec(location.href)[0],
  1052. base_path = location.pathname.replace(/\/[^\/]+\.[^\/]+$/, "/"),
  1053. root_domain = /^\w+\:\/\/\/?[^\/]+/.exec(root_page)[0],
  1054. absolute_regex = /^\w+\:\/\//;
  1055. src=src.replace(/\.\//,"");
  1056. if (/^\/\/\/?/.test(src)){
  1057. src = location.protocol + src;
  1058. }
  1059. else if (!absolute_regex.test(src) && src.charAt(0) != "/"){
  1060. src = (base_path || "") + src;
  1061. }
  1062. return (absolute_regex.test(src) ? src : ((src.charAt(0) == "/" ? root_domain : root_page) + src));
  1063. }
  1064.  
  1065. getLinkByPage(url, pageNum) {
  1066. if(!url)return;
  1067. if(this.curSiteRule.pageNum){
  1068. let result=this.curSiteRule.pageNum;
  1069. let strMatch=result.match(/\{.*?}/);
  1070. if(!strMatch)return null;
  1071. let urlReg=new RegExp("("+result.replace(strMatch[0], ")\\d+(")+")","i");
  1072. let code=strMatch[0].replace(/^{/,"").replace(/}$/,"").replace(/\$p/g,pageNum);
  1073. if(code==pageNum){
  1074. result=url.replace(urlReg,"$1"+code+"$2");
  1075. }else{
  1076. try{
  1077. code=Function('"use strict";return ' + code)();
  1078. result=url.replace(urlReg,"$1"+code+"$2");
  1079. }catch(e){
  1080. debug(e);
  1081. }
  1082. }
  1083. return result==url?url.replace(/([&\/\?](p=|page[=\/_-]?))\d+/i, "$1"+pageNum).replace(/([_-])\d+\./i, "$1"+pageNum+"."):result;
  1084. }else{
  1085. return url.replace(/([&\/\?](p=|page[=\/_-]?))\d+/i, "$1"+pageNum).replace(/([_-])\d+\./i, "$1"+pageNum+".");
  1086. }
  1087. }
  1088.  
  1089. getNextLink(doc) {
  1090. let nextLink=null,page,href;
  1091. let getNextLinkByForm=(form,n)=>{
  1092. let params=[];
  1093. [].forEach.call(form.querySelectorAll("input"), input=>{
  1094. if(n && /^(p|page)$/i.test(input.name)){
  1095. params.push('p='+n);
  1096. }else{
  1097. params.push(input.name+'='+input.value);
  1098. }
  1099. });
  1100. return form.action+'?'+params.join('&');
  1101. };
  1102. if(this.curSiteRule.pageElementByJs){
  1103. this.nextLinkHref="#";
  1104. return true;
  1105. }else if(this.curSiteRule.nextLinkByJs){
  1106. try{
  1107. let targetUrl=Function("doc",'"use strict";' + this.curSiteRule.nextLinkByJs)(doc);
  1108. if(targetUrl)nextLink={href:targetUrl};
  1109. }catch(e){
  1110. debug(e);
  1111. }
  1112. }else if(this.curSiteRule.nextLinkByUrl){
  1113. let targetUrl=this.curUrl.replace(new RegExp(this.curSiteRule.nextLinkByUrl[0],"i"), this.curSiteRule.nextLinkByUrl[1]);
  1114. if(targetUrl != this.curUrl){
  1115. let reps=targetUrl.match(/{.*?}/g);
  1116. if(reps){
  1117. reps.forEach(rep=>{
  1118. let code=rep.replace("{","").replace("}","");
  1119. let result=code.match(/^(\d+)\+1$/);
  1120. if(result){
  1121. result=parseInt(result[1])+1;
  1122. }else{
  1123. try{
  1124. result=Function('"use strict";return ' + code)();
  1125. }catch(e){
  1126. debug(e);
  1127. }
  1128. }
  1129. targetUrl=targetUrl.replace(rep, result);
  1130. });
  1131. }
  1132. }
  1133. nextLink={href:targetUrl};
  1134. }else if(this.curSiteRule.nextLink){
  1135. if(this.curSiteRule.nextLink!="0" && this.curSiteRule.nextLink!=0){
  1136. nextLink=this.curSiteRule.type==0?getElementByXpath(this.curSiteRule.nextLink,doc,doc):doc.querySelector(this.curSiteRule.nextLink);
  1137. }
  1138. }else{
  1139. page=this.getPage(doc);
  1140. nextLink=page.next;
  1141. if(nextLink){
  1142. if(nextLink.tagName=="INPUT" && nextLink.parentNode.tagName=="FORM"){
  1143. let form=nextLink.parentNode;
  1144. nextLink.href=getNextLinkByForm(form);
  1145. }
  1146. if(nextLink.parentNode.style.display=="none" || nextLink.style.display=="none" || nextLink.classList.contains("noClick") || nextLink.hasAttribute("disabled")){
  1147. this.nextLinkHref=false;
  1148. return null;
  1149. }else if(doc==document){
  1150. if((!nextLink.href || /^javascript:/.test(nextLink.href)) && !isVisible(nextLink, _unsafeWindow)){
  1151. this.nextLinkHref=false;
  1152. return null;
  1153. }else{
  1154. let nextLinkCs=_unsafeWindow.getComputedStyle(nextLink);
  1155. if(nextLinkCs.cursor=="not-allowed"){
  1156. this.nextLinkHref=false;
  1157. return null;
  1158. }
  1159. this.initNext=nextLink;
  1160. }
  1161. }
  1162. let form=doc.querySelector('#search-form');
  1163. if(!nextLink.href && nextLink.hasAttribute("onclick") && form){
  1164. if(form && /^\d+$/.test(nextLink.innerText)){
  1165. href=getNextLinkByForm(form, nextLink.innerText);
  1166. }
  1167. }
  1168. }
  1169. }
  1170. if(nextLink){
  1171. let needUrl=(this.curSiteRule.action==0 || this.curSiteRule.action==1);
  1172. if(!href)href=nextLink.href;
  1173. if(href && nextLink.getAttribute){
  1174. let _href=nextLink.getAttribute("href");
  1175. if(!_href || _href.charAt(0)=="#"){
  1176. href=_href;
  1177. }
  1178. }
  1179.  
  1180. if((href===""||href===null) && needUrl){
  1181. this.nextLinkHref=false;
  1182. }else if(/^(javascript:|#)/.test(href) && needUrl){
  1183. this.nextLinkHref=false;
  1184. }else{
  1185. this.nextLinkHref=(href && !/^(javascript:|#)/.test(href))?this.canonicalUri(href):"#";
  1186. if(this.nextLinkHref!="#" && (this.nextLinkHref==this.curUrl || this.nextLinkHref==this.curUrl+"#" || this.nextLinkHref==this.oldUrl || this.nextLinkHref==this.oldUrl+"#")){
  1187. this.nextLinkHref=false;
  1188. }else if(doc==document)debug(nextLink);
  1189. }
  1190. }else{
  1191. this.nextLinkHref=false;
  1192. }
  1193. this.preload();
  1194. return nextLink;
  1195. }
  1196.  
  1197. preload(){
  1198. if(!rulesData.preload)return;
  1199. if(!this.nextLinkHref || this.nextLinkHref=="#")return;
  1200. let self=this;
  1201. if(this.curSiteRule && this.curSiteRule.action==1){
  1202. if(!this.preloadIframe){
  1203. this.preloadIframe = document.createElement('iframe');
  1204. let iframe = this.preloadIframe;
  1205. iframe.name = 'pagetual-iframe';
  1206. iframe.width = '100%';
  1207. iframe.height = '0';
  1208. iframe.frameBorder = '0';
  1209. if(ruleParser.curSiteRule.sandbox!=false){
  1210. iframe.sandbox="allow-same-origin allow-scripts allow-popups allow-forms";
  1211. }
  1212. iframe.style.cssText = 'margin:0!important;padding:0!important;visibility:hidden!important;';
  1213. iframe.addEventListener('load', function (e) {
  1214. try{
  1215. let doc=iframe.contentDocument || iframe.contentWindow.document;
  1216. var body = doc.body;
  1217. if (body && body.firstChild) {
  1218. self.lazyImgAction(body.children);
  1219. }
  1220. }catch(e){
  1221. return;
  1222. }
  1223. }, false);
  1224. document.body.appendChild(iframe);
  1225. }
  1226. this.preloadIframe.src = this.nextLinkHref;
  1227. }else{
  1228. _GM_xmlhttpRequest({
  1229. url: this.nextLinkHref,
  1230. method: 'GET',
  1231. overrideMimeType: 'text/html;charset='+document.charset,
  1232. headers: {
  1233. 'Referer': location.href
  1234. },
  1235. timeout: 5000,
  1236. onload: function(res) {
  1237. var doc=null;
  1238. try {
  1239. doc=document.implementation.createHTMLDocument('');
  1240. doc.documentElement.innerHTML=res.response;
  1241. var body = doc.body;
  1242. if (body && body.firstChild) {
  1243. self.lazyImgAction(body.children);
  1244. }
  1245. if(!self.preloadDiv){
  1246. self.preloadDiv = document.createElement('div');
  1247. self.preloadDiv.id = "pagetual-preload";
  1248. self.preloadDiv.style.cssText = 'display:none!important;';
  1249. document.body.appendChild(self.preloadDiv);
  1250. self.checkedImgs={};
  1251. }
  1252. [].forEach.call(doc.images, i=>{
  1253. let iSrc=i.src;
  1254. if(iSrc && !self.checkedImgs[iSrc]){
  1255. self.checkedImgs[iSrc] = true;
  1256. let img = document.createElement('img');
  1257. img.src = iSrc;
  1258. self.preloadDiv.appendChild(img);
  1259. }
  1260. });
  1261. }
  1262. catch (e) {
  1263. return;
  1264. }
  1265. }
  1266. });
  1267. }
  1268. }
  1269.  
  1270. getInsert(refresh) {
  1271. if(refresh){
  1272. this.insert=null;
  1273. }
  1274. if(this.insert && !refresh){
  1275. let parent=this.insert;
  1276. while(parent && parent.nodeName!="BODY"){
  1277. parent=parent.parentNode;
  1278. }
  1279. if(parent && parent.nodeName=="BODY"){
  1280. return this.insert;
  1281. }
  1282. }
  1283. if(this.curSiteRule.insert){
  1284. this.insert=this.curSiteRule.type==0?getElementByXpath(this.curSiteRule.insert,document):document.querySelector(this.curSiteRule.insert);
  1285. }else{
  1286. let pageElement=this.getPageElement(document, _unsafeWindow);
  1287. if(pageElement && pageElement.length>0){
  1288. var pELast = pageElement[pageElement.length - 1];
  1289. this.insert = pELast.nextSibling ? pELast.nextSibling : pELast.parentNode.appendChild(document.createTextNode(' '));
  1290. }
  1291. }
  1292. return this.insert;
  1293. }
  1294.  
  1295. pageInit(doc,eles){
  1296. let code=this.curSiteRule.pageInit;
  1297. if(code){
  1298. try{
  1299. Function("doc","eles",'"use strict";' + code)(doc,eles);
  1300. }catch(e){
  1301. debug(e);
  1302. }
  1303. }
  1304. }
  1305.  
  1306. pageAction(doc,eles){
  1307. let code=this.curSiteRule.pageAction;
  1308. if(code){
  1309. try{
  1310. Function("doc","eles",'"use strict";' + code)(doc,eles);
  1311. }catch(e){
  1312. debug(e);
  1313. }
  1314. }
  1315. this.lazyImgAction(eles);
  1316. this.openInNewTab(eles);
  1317. }
  1318.  
  1319. openInNewTab(eles){
  1320. if(rulesData.openInNewTab){
  1321. [].forEach.call(eles, ele=>{
  1322. if(ele.tagName=="A" && ele.href && !/^(mailto:|javascript:|#)/.test(ele.href)){
  1323. ele.setAttribute('target', '_blank');
  1324. }else{
  1325. [].forEach.call(ele.querySelectorAll('a[href]:not([href^="mailto:"]):not([href^="javascript:"]):not([href^="#"])'), a=>{
  1326. a.setAttribute('target', '_blank');
  1327. if (a.getAttribute('onclick') == 'atarget(this)') {
  1328. a.removeAttribute('onclick');
  1329. }
  1330. });
  1331. }
  1332. });
  1333. }
  1334. }
  1335.  
  1336. lazyImgAction(eles){
  1337. let setLazyImg=img=>{
  1338. let realSrc;
  1339. if(img.getAttribute("_src") && !img.src){
  1340. realSrc=img.getAttribute("_src");
  1341. }else if(img.dataset && img.dataset.original){
  1342. realSrc=img.dataset.original;
  1343. }else if(img.dataset && img.dataset.src){
  1344. realSrc=img.dataset.src;
  1345. }else if(img._lazyrias && img._lazyrias.srcset){
  1346. realSrc=img._lazyrias.srcset[img._lazyrias.srcset.length-1];
  1347. }else if(img.dataset && img.dataset.origFile){
  1348. realSrc=img.dataset.origFile;
  1349. }else if(img.srcset){
  1350. var srcs=img.srcset.split(/[xw],/),largeSize=0;
  1351. srcs.forEach(srci=>{
  1352. let srcInfo=srci.trim().split(" "),curSize=parseInt(srcInfo[1]);
  1353. if(srcInfo[1] && curSize>largeSize){
  1354. largeSize=curSize;
  1355. realSrc=srcInfo[0];
  1356. }
  1357. });
  1358. }
  1359. if(realSrc){
  1360. img.src=realSrc;
  1361. img.style.display="block";
  1362. }
  1363. };
  1364. [].forEach.call(eles, ele=>{
  1365. if(ele.tagName=="IMG"){
  1366. setLazyImg(ele);
  1367. }else{
  1368. [].forEach.call(ele.querySelectorAll("img"), img=>{
  1369. setLazyImg(img);
  1370. });
  1371. }
  1372. if(ele.tagName=="A" && ele.classList.contains("lazyload")){
  1373. if(ele.dataset.original){
  1374. ele.style.backgroundImage='url("'+ele.dataset.original+'")';
  1375. }
  1376. }else{
  1377. [].forEach.call(ele.querySelectorAll("a.lazyload"), a=>{
  1378. if(a.dataset.original){
  1379. a.style.backgroundImage='url("'+a.dataset.original+'")';
  1380. }
  1381. });
  1382. }
  1383. });
  1384. let lazyImgSrc=this.curSiteRule.lazyImgSrc;
  1385. if(lazyImgSrc){
  1386. [].forEach.call(eles, ele=>{
  1387. [].forEach.call(ele.querySelectorAll("img"), img=>{
  1388. if(img.getAttribute(lazyImgSrc)){
  1389. img.src=img.getAttribute(lazyImgSrc);
  1390. }
  1391. });
  1392. });
  1393. }
  1394. }
  1395.  
  1396. initPage(callback){
  1397. let self=this;
  1398. curPage=1;
  1399. //if(this.curSiteRule.url && !this.curSiteRule.singleUrl)return;
  1400. this.curSiteRule={};
  1401. this.pageDoc=document;
  1402. this.nextLinkHref=null;
  1403. this.curUrl=location.href;
  1404. this.getRule(()=>{
  1405. if(self.curSiteRule.enable==0){
  1406. debug("Stop as rule disable");
  1407. isPause=true;
  1408. return;
  1409. }
  1410. if(self.curSiteRule && !self.curSiteRule.singleUrl){
  1411. self.hpRules=self.hpRules.filter(item=>{return item&&item.url!=self.curSiteRule.url});
  1412. self.hpRules.unshift(self.curSiteRule);
  1413. if(self.hpRules.length>30){
  1414. self.hpRules.pop();
  1415. }
  1416. storage.setItem("hpRules", self.hpRules);
  1417. }
  1418. let css=self.curSiteRule.css;
  1419. if(css){
  1420. _GM_addStyle(css);
  1421. }
  1422. let autoClick=self.curSiteRule.autoClick;
  1423. if(autoClick){
  1424. let autoClickBtn;
  1425. try{
  1426. autoClickBtn=document.querySelector(autoClick);
  1427. }catch(e){
  1428. autoClickBtn=getElementByXpath(autoClick);
  1429. }
  1430. if(autoClickBtn){
  1431. emuClick(autoClickBtn);
  1432. }
  1433. }
  1434. let code=self.curSiteRule.init;
  1435. if(code){
  1436. try{
  1437. Function('doc','win','iframe','"use strict";' + code)(null,null,null);
  1438. }catch(e){
  1439. debug(e);
  1440. }
  1441. }
  1442. self.getNextLink(document);
  1443. callback();
  1444. });
  1445. }
  1446.  
  1447. insertPage(doc, eles, url, callback, tried){
  1448. this.oldUrl=this.curUrl;
  1449. let oldTitle=this.pageDoc.title;
  1450. this.pageDoc=doc;
  1451. this.curUrl=url;
  1452. let nextLink=this.getNextLink(doc);
  1453. this.nextTitle="";
  1454. if(this.curSiteRule.pageBarText){
  1455. if(this.curSiteRule.pageBarText==1){
  1456. this.nextTitle=doc.title;
  1457. }else{
  1458. try{
  1459. this.nextTitle=Function("doc",'"use strict";' + this.curSiteRule.pageBarText)(doc);
  1460. }catch(e){
  1461. debug(e);
  1462. }
  1463. }
  1464. }
  1465. if(curPage==1 && !tried && !nextLink && this.curSiteRule.singleUrl && this.curSiteRule.pageElement && this.curSiteRule.action!=0){
  1466. this.curSiteRule.action=1;
  1467. this.curUrl=location.href;
  1468. return false;
  1469. }
  1470. if(callback)callback(eles);
  1471. this.getInsert();
  1472. var self=this,newEles=[];
  1473. if(!eles || eles.length==0 || !self.insert || !self.insert.parentNode){
  1474. }else{
  1475. this.pageInit(doc, eles);
  1476. [].forEach.call(eles, ele=>{
  1477. let newEle=ele.cloneNode(true);
  1478. let oldCanvass=ele.querySelectorAll("canvas");
  1479. let newCanvass=newEle.querySelectorAll("canvas");
  1480. for(let i=0;i<oldCanvass.length;i++){
  1481. let oldCanvas=oldCanvass[i];
  1482. let newCanvas=newCanvass[i];
  1483. newCanvas.getContext('2d').drawImage(oldCanvas, 0, 0);
  1484. }
  1485. if(self.curSiteRule.insertPos==2){
  1486. self.insert.appendChild(newEle);
  1487. }else{
  1488. self.insert.parentNode.insertBefore(newEle, self.insert);
  1489. }
  1490. newEles.push(newEle);
  1491. });
  1492. }
  1493. this.pageAction(doc, newEles);
  1494. if(this.oldUrl!=location.href){
  1495. let isJs=/^(javascript|#)/.test(this.oldUrl.replace(location.href,""));
  1496. if(rulesData.enableHistory && !isJs){
  1497. _unsafeWindow.history.replaceState(undefined, oldTitle, this.oldUrl);
  1498. document.title=oldTitle;
  1499. }
  1500. }
  1501. return true;
  1502. }
  1503. }
  1504. var ruleParser = new RuleParser();
  1505.  
  1506. function initConfig(){
  1507. initView();
  1508. _GM_registerMenuCommand(i18n(forceState==1?"enable":"disableSite"), ()=>{
  1509. storage.setItem("forceState_"+location.host, (forceState==1?0:1));
  1510. location.reload();
  1511. });
  1512. _GM_registerMenuCommand(i18n("update"), ()=>{
  1513. updateRules(()=>{
  1514. showTips(i18n("updateSucc"));
  1515. location.reload();
  1516. },(rule,err)=>{
  1517. showTips("Update "+rule.url+" rules fail!");
  1518. });
  1519. showTips(i18n("beginUpdate"));
  1520. });
  1521.  
  1522. var configCon,insertPos;
  1523. if(ruleImportUrlReg.test(location.href)){
  1524. document.addEventListener("click", e=>{
  1525. if(e.target.tagName=="PRE"){
  1526. let nameAttr=e.target.getAttribute("name");
  1527. if(nameAttr=="pagetual" || nameAttr=="user-content-pagetual" || location.href.indexOf("greasyfork.org") != -1){
  1528. let rules=e.target.innerText.trim();
  1529. let isContent=/['"]name['"]/i.test(rules);
  1530. if(isContent){
  1531. let ruleList=JSON.parse(`[${rules}]`);
  1532. for(let i in ruleList){
  1533. let hasRule = false;
  1534. let r = ruleList[i];
  1535. for(let j in ruleParser.customRules){
  1536. if(ruleParser.customRules[j].name == r.name){
  1537. ruleParser.customRules[j] = r;
  1538. hasRule = true;
  1539. break;
  1540. }
  1541. }
  1542. if(!hasRule)ruleParser.customRules.push(r);
  1543. }
  1544. storage.setItem("customRules", ruleParser.customRules);
  1545. showTips(i18n("importSucc"));
  1546. }else{
  1547. rules=rules.split("\n");
  1548. let diff=false;
  1549. for(let c=0;c<rules.length;c++){
  1550. let urlArr=rules[c].split("|"),url,type=1;
  1551. if(urlArr.length==1){
  1552. url=urlArr[0].trim();
  1553. if(!/^http/.test(url)){
  1554. showTips("Wrong url, check again!");
  1555. return;
  1556. }
  1557. }else if(urlArr.length==2){
  1558. type=urlArr[0].trim();
  1559. url=urlArr[1].trim();
  1560. if(!/^http/.test(url)){
  1561. showTips("Wrong url, check again!");
  1562. return;
  1563. }
  1564. }else{
  1565. break;
  1566. }
  1567. let maxId=0,hasUrl=false;
  1568. if(!rulesData.urls){
  1569. rulesData.urls=[];
  1570. maxId=1;
  1571. }else{
  1572. rulesData.urls.forEach(u=>{
  1573. if(maxId<u.id){
  1574. maxId=u.id;
  1575. }
  1576. if(u.url==url){
  1577. hasUrl=true;
  1578. }
  1579. });
  1580. if(hasUrl)break;
  1581. }
  1582. diff=true;
  1583. if(!rulesData.sort)rulesData.sort=[1];
  1584. rulesData.urls.push({id:maxId+1,url:url,type:type});
  1585. rulesData.sort.unshift(maxId+1);
  1586. }
  1587. if(!diff)return;
  1588. storage.setItem("rulesData", rulesData);
  1589.  
  1590. if(rulesData.urls)ruleUrls=ruleUrls.concat(rulesData.urls);
  1591. if(rulesData.sort){
  1592. let urls=[];
  1593. rulesData.sort.forEach(id=>{
  1594. for(let s=0;s<ruleUrls.length;s++){
  1595. if(id==ruleUrls[s].id){
  1596. urls.push(ruleUrls[s]);
  1597. break;
  1598. }
  1599. }
  1600. });
  1601. ruleUrls=urls;
  1602. }
  1603. updateRules(()=>{
  1604. showTips(i18n("updateSucc"));
  1605. },(rule,err)=>{
  1606. showTips("Update "+rule.url+" rules fail!");
  1607. });
  1608. showTips(i18n("beginUpdate"));
  1609. }
  1610. }
  1611. }
  1612. });
  1613. }
  1614. if(location.href==configPage){
  1615. _GM_addStyle(`
  1616. p>span:nth-child(1),p>span:nth-child(2),p>span:nth-child(3){
  1617. cursor: pointer;
  1618. user-select: none;
  1619. }
  1620. p>span:nth-child(1):hover,p>span:nth-child(2):hover,p>span:nth-child(3):hover{
  1621. color:red;
  1622. }
  1623. .updateDate{
  1624. cursor: pointer;
  1625. user-select: none;
  1626. }
  1627. .updateDate:hover{
  1628. color:red;
  1629. }
  1630. `);
  1631. document.querySelector("[name='user-content-click2import']").innerText=i18n("click2ImportRule")
  1632. configCon=document.querySelector(".markdown-body");
  1633. insertPos=configCon.querySelector("hr");
  1634.  
  1635. if(rulesData.urls && rulesData.urls.length>0){
  1636. document.querySelector("pre[name='user-content-pagetual']").style.display="none";
  1637. document.querySelector("p[name='user-content-click2import']").style.display="none";
  1638. }
  1639. }else return false;
  1640. class Rulebar {
  1641. init(ruleUrl){
  1642. this.ruleUrl=ruleUrl;
  1643. this.item=document.createElement("p");
  1644. this.item.title=ruleUrl.type==0?"AutoPagerize Rules":"Pagetual Rules";
  1645. this.item.dataset.id=this.ruleUrl.id;
  1646. let url=document.createElement("span");
  1647. url.innerHTML=ruleUrl.url;
  1648. let up=document.createElement("span");
  1649. up.innerHTML="↑ ";
  1650. up.title=i18n("sortTitle");
  1651. let down=document.createElement("span");
  1652. down.innerHTML="↓ ";
  1653. down.title=i18n("sortTitle");
  1654. let del=document.createElement("span");
  1655. del.innerHTML="× ";
  1656. up.onclick=e=>{
  1657. this.moveUp();
  1658. };
  1659. down.onclick=e=>{
  1660. this.moveDown();
  1661. };
  1662. del.onclick=e=>{
  1663. this.del();
  1664. };
  1665. this.item.appendChild(up);
  1666. this.item.appendChild(down);
  1667. this.item.appendChild(del);
  1668. this.item.appendChild(url);
  1669. configCon.insertBefore(this.item, insertPos);
  1670. }
  1671. saveSort(){
  1672. let sort=[];
  1673. [].forEach.call(this.item.parentNode.querySelectorAll("p[data-id]"), i=>{
  1674. sort.push(i.dataset.id);
  1675. });
  1676. rulesData.sort=sort;
  1677. storage.setItem("rulesData", rulesData);
  1678. }
  1679. moveUp(){
  1680. let preE=this.item.previousElementSibling;
  1681. if(preE.tagName=="P" && preE.children.length>1){
  1682. this.item.parentNode.insertBefore(this.item,preE);
  1683. this.saveSort();
  1684. }
  1685. }
  1686. moveDown(){
  1687. let nextE=this.item.nextElementSibling;
  1688. if(nextE.tagName=="P" && nextE.children.length>1){
  1689. this.item.parentNode.insertBefore(nextE,this.item);
  1690. this.saveSort();
  1691. }
  1692. }
  1693. del(){
  1694. if(this.ruleUrl.id<2){
  1695. showTips(i18n("cantDel"));
  1696. }else if(window.confirm(i18n("confirmDel"))){
  1697. for(let u=0;u<rulesData.urls.length;u++){
  1698. if(this.ruleUrl.id==rulesData.urls[u].id){
  1699. rulesData.urls.splice(u,1);
  1700. break;
  1701. }
  1702. }
  1703. for(let u=0;u<rulesData.sort.length;u++){
  1704. if(this.ruleUrl.id==rulesData.sort[u]){
  1705. rulesData.sort.splice(u,1);
  1706. break;
  1707. }
  1708. }
  1709. storage.setItem("rulesData", rulesData);
  1710. ruleParser.rules=ruleParser.rules.filter(item=>{return item.from!=this.ruleUrl.id});
  1711. storage.setItem("rules", ruleParser.rules);
  1712. this.item.parentNode.removeChild(this.item);
  1713. //location.reload();
  1714. }
  1715. }
  1716. }
  1717. let updateP=document.createElement("p"),i=0;
  1718. let now=new Date().getTime(),inUpdate=false;
  1719.  
  1720.  
  1721. let pastDate=(new Date(updateDate)).toString(),passStr;
  1722. let passTime=(now-updateDate)/1000;
  1723. if(isNaN(passTime)){
  1724. passStr=i18n("firstUpdate");
  1725. }else if(passTime<60){
  1726. passStr=i18n("passSec", parseInt(passTime))+" ← "+i18n("click2update");
  1727. }else if(passTime<60*60){
  1728. passStr=i18n("passMin", parseInt(passTime/60))+" ← "+i18n("click2update");
  1729. }else if(passTime<60*60*24){
  1730. passStr=i18n("passHour", parseInt(passTime/3600))+" ← "+i18n("click2update");
  1731. }else{
  1732. passStr=i18n("passDay", parseInt(passTime/86400))+" ← "+i18n("click2update");
  1733. }
  1734.  
  1735.  
  1736. updateP.className="updateDate";
  1737. updateP.innerHTML=passStr;
  1738. updateP.title=i18n("update")+" - "+pastDate;
  1739. updateP.onclick=e=>{
  1740. updateRules(()=>{
  1741. showTips(i18n("updateSucc"));
  1742. updateP.innerHTML=i18n("passSec", 0);
  1743. updateP.title=i18n("update");
  1744. },(rule,err)=>{
  1745. showTips("Update "+rule.url+" rules fail!");
  1746. });
  1747. showTips(i18n("beginUpdate"));
  1748. };
  1749. configCon.insertBefore(updateP, insertPos);
  1750. if(ruleUrls){
  1751. ruleUrls.forEach(ruleUrl=>{
  1752. var rulebar=new Rulebar();
  1753. rulebar.init(ruleUrl);
  1754. });
  1755. }
  1756. let customUrlsTitle=document.createElement("h2");
  1757. customUrlsTitle.innerHTML=i18n("customUrls");
  1758. configCon.insertBefore(customUrlsTitle, insertPos);
  1759. let customUrlsInput=document.createElement("textarea");
  1760. customUrlsInput.style.width="100%";
  1761. customUrlsInput.placeholder="0 | http://wedata.net/databases/AutoPagerize/items_all.json";
  1762. configCon.insertBefore(customUrlsInput, insertPos);
  1763.  
  1764. let upBtnImgTitle=document.createElement("h2");
  1765. upBtnImgTitle.innerHTML=i18n("upBtnImg");
  1766. upBtnImgTitle.style.width="50%";
  1767. upBtnImgTitle.style.float="left";
  1768. let upBtnImgInput=document.createElement("input");
  1769. upBtnImgInput.style.width="100%";
  1770. upBtnImgInput.placeholder="data:image/png;base64,UpBtn";
  1771. upBtnImgInput.value=rulesData.upBtnImg||'';
  1772. upBtnImgTitle.appendChild(upBtnImgInput);
  1773. configCon.insertBefore(upBtnImgTitle, insertPos);
  1774.  
  1775. let downBtnImgTitle=document.createElement("h2");
  1776. downBtnImgTitle.innerHTML=i18n("downBtnImg");
  1777. downBtnImgTitle.style.width="50%";
  1778. downBtnImgTitle.style.float="left";
  1779. let downBtnImgInput=document.createElement("input");
  1780. downBtnImgInput.style.width="100%";
  1781. downBtnImgInput.placeholder="data:image/png;base64,DownBtn";
  1782. downBtnImgInput.value=rulesData.downBtnImg||'';
  1783. downBtnImgTitle.appendChild(downBtnImgInput);
  1784. configCon.insertBefore(downBtnImgTitle, insertPos);
  1785.  
  1786. let opacityTitle=document.createElement("h2");
  1787. opacityTitle.innerHTML=i18n("opacity");
  1788. let opacityInput=document.createElement("input");
  1789. opacityInput.value=rulesData.opacity*100;
  1790. opacityInput.type="number";
  1791. opacityInput.style.width="50px";
  1792. opacityInput.style.margin="0 0 0 10px";
  1793. opacityTitle.appendChild(opacityInput);
  1794. configCon.insertBefore(opacityTitle, insertPos);
  1795.  
  1796. let configTable=document.createElement("table");
  1797. configTable.appendChild(document.createElement("tbody"));
  1798. configCon.insertBefore(configTable, insertPos);
  1799. function createCheckbox(innerText, val){
  1800. let title=document.createElement("h3");
  1801. title.innerHTML=innerText;
  1802. let input=document.createElement("input");
  1803. input.type="checkbox";
  1804. input.style.width="50px";
  1805. input.style.height="20px";
  1806. input.checked=val;
  1807. let tr=document.createElement("tr");
  1808. let td=document.createElement("td");
  1809. td.appendChild(input);
  1810. tr.appendChild(td);
  1811. td=document.createElement("td");
  1812. td.appendChild(title);
  1813. tr.appendChild(td);
  1814. configTable.children[0].appendChild(tr);
  1815. return input;
  1816. }
  1817.  
  1818. let hideBarInput=createCheckbox(i18n("hideBar"), rulesData.hideBar);
  1819. let dbClick2StopInput=createCheckbox(i18n("dbClick2Stop"), rulesData.dbClick2Stop);
  1820. let enableWhiteListInput=createCheckbox(i18n("autoRun"), rulesData.enableWhiteList!=true);
  1821. let enableDebugInput=createCheckbox(i18n("enableDebug"), rulesData.enableDebug!=false);
  1822. let enableHistoryInput=createCheckbox(i18n("enableHistory"), rulesData.enableHistory===true);
  1823. let openInNewTabInput=createCheckbox(i18n("openInNewTab"), rulesData.openInNewTab!=false);
  1824. let initRunInput=createCheckbox(i18n("initRun"), rulesData.initRun!=false);
  1825. let preloadInput=createCheckbox(i18n("preload"), rulesData.preload!=false);
  1826.  
  1827. let customRulesTitle=document.createElement("h2");
  1828. customRulesTitle.innerHTML=i18n("customRules");
  1829. configCon.insertBefore(customRulesTitle, insertPos);
  1830. let customRulesInput=document.createElement("textarea");
  1831. configCon.insertBefore(customRulesInput, insertPos);
  1832. if(rulesData.editTemp){
  1833. if(!ruleParser.customRules){
  1834. ruleParser.customRules=[];
  1835. }
  1836. for(let i in ruleParser.customRules){
  1837. if(ruleParser.customRules[i].url==rulesData.editTemp.url){
  1838. ruleParser.customRules.splice(i, 1);
  1839. break;
  1840. }
  1841. }
  1842. ruleParser.customRules.unshift(rulesData.editTemp);
  1843. rulesData.editTemp=null;
  1844. storage.setItem("rulesData", rulesData);
  1845. customRulesInput.scrollIntoView();
  1846. }
  1847. customRulesInput.style.width="100%";
  1848. customRulesInput.style.height="500px";
  1849. 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]`;
  1850. customRulesInput.value=getFormatJSON(ruleParser.customRules);
  1851. let blacklistInput=document.createElement("textarea");
  1852. blacklistInput.style.width="100%";
  1853. blacklistInput.style.height="500px";
  1854. blacklistInput.style.display="none";
  1855. blacklistInput.placeholder="http://*.xxx.com/*/y";
  1856. blacklistInput.value=rulesData.blacklist?rulesData.blacklist.join("\n"):"";
  1857. let blacklistBtn=document.createElement("button");
  1858. blacklistBtn.innerText=i18n("editBlacklist");
  1859. blacklistBtn.style.width="100%";
  1860. blacklistBtn.onclick=e=>{
  1861. blacklistInput.style.display=blacklistInput.style.display=="none"?"":"none";
  1862. };
  1863. configCon.insertBefore(blacklistBtn, insertPos);
  1864. configCon.insertBefore(blacklistInput, insertPos);
  1865. let saveBtn=document.createElement("button");
  1866. saveBtn.innerHTML=i18n("save");
  1867. saveBtn.style.width="100%";
  1868. configCon.insertBefore(saveBtn, insertPos);
  1869. saveBtn.onclick=e=>{
  1870. try{
  1871. storage.setItem("hpRules", []);
  1872. if(customRulesInput.value==""){
  1873. storage.setItem("customRules", "");
  1874. }else{
  1875. let customRules=JSON.parse(customRulesInput.value);
  1876. if(Array && Array.isArray && !Array.isArray(customRules)){
  1877. showTips("Rules must be a Array!");
  1878. return;
  1879. }
  1880. debug(customRules);
  1881. storage.setItem("customRules", customRules);
  1882. }
  1883. }catch(e){
  1884. debug(e);
  1885. showTips("JSON error, check again!");
  1886. return;
  1887. }
  1888. rulesData.opacity=opacityInput.value/100;
  1889. rulesData.blacklist=blacklistInput.value?blacklistInput.value.split("\n"):"";
  1890. rulesData.hideBar=hideBarInput.checked;
  1891. rulesData.dbClick2Stop=dbClick2StopInput.checked;
  1892. rulesData.enableWhiteList=!enableWhiteListInput.checked;
  1893. rulesData.enableDebug=enableDebugInput.checked;
  1894. rulesData.enableHistory=enableHistoryInput.checked;
  1895. rulesData.openInNewTab=openInNewTabInput.checked;
  1896. rulesData.initRun=initRunInput.checked;
  1897. rulesData.preload=preloadInput.checked;
  1898. rulesData.upBtnImg=upBtnImgInput.value;
  1899. rulesData.downBtnImg=downBtnImgInput.value;
  1900. storage.setItem("rulesData", rulesData);
  1901. let customUrls=customUrlsInput.value.trim();
  1902. if(customUrls){
  1903. customUrls=customUrls.split(/\n/);
  1904. for(let c=0;c<customUrls.length;c++){
  1905. let urlArr=customUrls[c].split("|"),url,type=1;
  1906. if(urlArr.length==1){
  1907. url=urlArr[0].trim();
  1908. if(!/^http/.test(url)){
  1909. showTips("Wrong url, check again!");
  1910. return;
  1911. }
  1912. }else if(urlArr.length==2){
  1913. type=urlArr[0].trim();
  1914. url=urlArr[1].trim();
  1915. if(!/^http/.test(url)){
  1916. showTips("Wrong url, check again!");
  1917. return;
  1918. }
  1919. }else{
  1920. break;
  1921. }
  1922. let maxId=0,hasUrl=false;
  1923. if(!rulesData.urls){
  1924. rulesData.urls=[];
  1925. maxId=1;
  1926. }else{
  1927. rulesData.urls.forEach(u=>{
  1928. if(maxId<u.id){
  1929. maxId=u.id;
  1930. }
  1931. if(u.url==url){
  1932. hasUrl=true;
  1933. }
  1934. });
  1935. if(hasUrl)break;
  1936. }
  1937. if(!rulesData.sort)rulesData.sort=[1];
  1938. rulesData.urls.push({id:maxId+1,url:url,type:type});
  1939. rulesData.sort.push(maxId+1);
  1940. storage.setItem("rulesData", rulesData);
  1941. }
  1942. }
  1943. showTips("The settings are saved");
  1944. location.reload();
  1945. };
  1946. return true;
  1947. }
  1948.  
  1949. var inUpdate=false;
  1950. function updateRules(success,fail){
  1951. if(inUpdate)return;
  1952. inUpdate=true;
  1953. let ruleIndex=ruleUrls.length-1;
  1954. storage.setItem("hpRules", []);
  1955. function addNextRule(){
  1956. if(ruleIndex<0){
  1957. let now=new Date().getTime();
  1958. storage.setItem("ruleLastUpdate", now);
  1959. storage.setItem("rules", ruleParser.rules);
  1960. inUpdate=false;
  1961. success();
  1962. }else{
  1963. let rule=ruleUrls[ruleIndex--];
  1964. ruleParser.addRuleByUrl(rule.url, rule.type, rule.id, (json,err)=>{
  1965. if(!json){
  1966. fail(rule,err);
  1967. }
  1968. addNextRule();
  1969. })
  1970. }
  1971. }
  1972. addNextRule();
  1973. }
  1974.  
  1975. function objIsArr(obj) {
  1976. return obj &&
  1977. typeof obj === 'object' &&
  1978. typeof obj.length === 'number' &&
  1979. !(obj.propertyIsEnumerable('length'));
  1980. }
  1981.  
  1982. function isVisible(el, win) {
  1983. if(!el.offsetParent)return false;
  1984. var loopable = true,
  1985. visible = el.tagName && win.getComputedStyle(el).display != 'none' && win.getComputedStyle(el).visibility != 'hidden';
  1986. while(loopable && visible) {
  1987. el = el.parentNode;
  1988.  
  1989. if(el && el.tagName && el.tagName!="BODY") {
  1990. visible = win.getComputedStyle(el).display != 'none' && win.getComputedStyle(el).visibility != 'hidden';
  1991. }else {
  1992. loopable = false;
  1993. }
  1994. }
  1995. return visible;
  1996. }
  1997.  
  1998. function getElementTop(ele) {
  1999. var actualTop = ele.offsetTop;
  2000. var current = ele.offsetParent;
  2001. while (current) {
  2002. actualTop += current.offsetTop;
  2003. current = current.offsetParent;
  2004. }
  2005. return actualTop;
  2006. }
  2007.  
  2008. function getFormatJSON(obj){
  2009. if(!objIsArr(obj))return "";
  2010. let ret="[\n";
  2011. let len=obj.length,i=0,isLast;
  2012. obj.forEach(item=>{
  2013. ret+=" {\n";
  2014. let iLen=Object.keys(item).length,j=0;
  2015. for(let key in item){
  2016. isLast=(++j)==iLen;
  2017. let value=item[key];
  2018. if(objIsArr(value)){
  2019. let vstr="[",v=0,vIsLast=false;
  2020. value.forEach(vi=>{
  2021. vIsLast=(++v)==value.length;
  2022. vstr+="\""+vi.replace(/\\/g,"\\\\")+"\""+(vIsLast?"":",");
  2023. });
  2024. vstr+="]";
  2025. ret+=" \""+key+"\":"+vstr+""+(isLast?"":",")+"\n";
  2026. }else{
  2027. if(typeof value=="string"){
  2028. value=value.replace(/\\/g,"\\\\").replace(/"/g,"\\\"");
  2029. value="\""+value+"\"";
  2030. }
  2031. ret+=" \""+key+"\":"+value+""+(isLast?"":",")+"\n";
  2032. }
  2033. }
  2034. isLast=(++i)==len;
  2035. ret+=" }"+(isLast?"":",")+"\n";
  2036. });
  2037. ret+="]";
  2038. return ret;
  2039. }
  2040.  
  2041. function globMatch(first, second) {
  2042. if (first.length == 0 && second.length == 0){
  2043. return true;
  2044. }
  2045.  
  2046. if (first.length > 1 && first[0] == '*' &&
  2047. second.length == 0){
  2048. return false;
  2049. }
  2050.  
  2051. if ((first.length > 1 && first[0] == '?') ||
  2052. (first.length != 0 && second.length != 0 &&
  2053. first[0] == second[0])){
  2054. return globMatch(first.substring(1),
  2055. second.substring(1));
  2056. }
  2057.  
  2058. if (first.length > 0 && first[0] == '*'){
  2059. return globMatch(first.substring(1), second) ||
  2060. globMatch(first, second.substring(1));
  2061. }
  2062.  
  2063. return false;
  2064. }
  2065.  
  2066. function initRules(callback) {
  2067. /*0 wedata格式,1 pagetual格式*/
  2068. ruleUrls=[
  2069. {
  2070. id:1,
  2071. url:'http://wedata.net/databases/AutoPagerize/items_all.json',
  2072. type:0,
  2073. }
  2074. ];var i=0,j=0;
  2075.  
  2076. ruleParser.initSavedRules(()=>{
  2077. storage.getItem("rulesData", data=>{
  2078. if(data){
  2079. rulesData=data;
  2080. if(data.urls)ruleUrls=ruleUrls.concat(data.urls);
  2081. if(data.sort){
  2082. let urls=[];
  2083. data.sort.forEach(id=>{
  2084. for(let s=0;s<ruleUrls.length;s++){
  2085. if(id==ruleUrls[s].id){
  2086. urls.push(ruleUrls[s]);
  2087. break;
  2088. }
  2089. }
  2090. });
  2091. ruleUrls=urls;
  2092. }
  2093. }
  2094. if(rulesData.upBtnImg){
  2095. upSvg=`<img src="${rulesData.upBtnImg}"/>`;
  2096. }
  2097. if(rulesData.downBtnImg){
  2098. downSvg=`<img src="${rulesData.downBtnImg}"/>`;
  2099. }
  2100. if(typeof(rulesData.opacity)=="undefined"){
  2101. rulesData.opacity=0.3;
  2102. }
  2103. if(typeof(rulesData.hideBar)=="undefined"){
  2104. rulesData.hideBar=false;
  2105. }
  2106. if(typeof(rulesData.dbClick2Stop)=="undefined"){
  2107. rulesData.dbClick2Stop=true;
  2108. }
  2109. if(typeof(rulesData.enableWhiteList)=="undefined"){
  2110. rulesData.enableWhiteList=false;
  2111. }
  2112. if(typeof(rulesData.enableHistory)=="undefined"){
  2113. rulesData.enableHistory=false;
  2114. }
  2115. if(typeof(rulesData.openInNewTab)=="undefined"){
  2116. rulesData.openInNewTab=true;
  2117. }
  2118. if(typeof(rulesData.enableDebug)=="undefined"){
  2119. rulesData.enableDebug=true;
  2120. }
  2121. if(typeof(rulesData.initRun)=="undefined"){
  2122. rulesData.initRun=true;
  2123. }
  2124. if(typeof(rulesData.preload)=="undefined"){
  2125. rulesData.preload=true;
  2126. }
  2127. if(rulesData.blacklist && rulesData.blacklist.length>0){
  2128. for(let b in rulesData.blacklist){
  2129. let curGlob=rulesData.blacklist[b];
  2130. if(globMatch(curGlob, location.href)){
  2131. return;
  2132. }
  2133. }
  2134. }
  2135. enableDebug=rulesData.enableDebug;
  2136. storage.getItem("forceState_"+location.host, v=>{
  2137. storage.getItem("ruleLastUpdate", date=>{
  2138. if(typeof(v)=="undefined"){
  2139. v=(rulesData.enableWhiteList?1:0);
  2140. }
  2141. forceState=v;
  2142. updateDate=date;
  2143. if(initConfig())return;
  2144. if(forceState==1)return;
  2145. let now=new Date().getTime();
  2146. if(!date || now-date>2*24*60*60*1000){
  2147. updateRules(()=>{
  2148. },(rule,err)=>{});
  2149. }
  2150. callback();
  2151. });
  2152. });
  2153. });
  2154. });
  2155. }
  2156.  
  2157. function requestDoc(url, callback){
  2158. _GM_xmlhttpRequest({
  2159. url: url,
  2160. method: 'GET',
  2161. overrideMimeType: 'text/html;charset='+document.charset,
  2162. headers: {
  2163. 'Referer': location.href,
  2164. "Content-Type": "text/html;charset="+document.charset,
  2165. },
  2166. timeout: 5000,
  2167. onload: function(res) {
  2168. var doc=null,response=res.response;
  2169. let preCode=ruleParser.curSiteRule.pageElementPre || ruleParser.curSiteRule.pagePre;
  2170. if(preCode){
  2171. try{
  2172. response=Function("response",'"use strict";' + preCode)(response);
  2173. }catch(e){
  2174. debug(e);
  2175. }
  2176. }
  2177. try {
  2178. doc=document.implementation.createHTMLDocument('');
  2179. doc.documentElement.innerHTML=response;
  2180. }
  2181. catch (e) {
  2182. debug('parse error'+e.toString());
  2183. }
  2184. let pageElement=ruleParser.getPageElement(doc);
  2185. if(inCors && (!pageElement || pageElement.length==0)){
  2186. ruleParser.curSiteRule.pageElement=allOfBody;
  2187. pageElement=ruleParser.getPageElement(doc);
  2188. ruleParser.getInsert(true);
  2189. }
  2190. //只有1的話怕不是圖片哦
  2191. if(pageElement && (pageElement.length>1 || (pageElement.length==1 && pageElement[0].tagName!="IMG") )){
  2192. let result=ruleParser.insertPage(doc, pageElement, url, callback, false);
  2193. ruleParser.curSiteRule.action=0;
  2194. if(!result){
  2195. ruleParser.curSiteRule.action=1;
  2196. requestFromIframe(url, (doc, eles)=>{
  2197. loadPageOver();
  2198. if(eles){
  2199. ruleParser.insertPage(doc, eles, url, callback, true);
  2200. }
  2201. });
  2202. }
  2203. }else if(ruleParser.curSiteRule.singleUrl || curPage==1){
  2204. ruleParser.curSiteRule.action=1;
  2205. requestFromIframe(url, (doc, eles)=>{
  2206. loadPageOver();
  2207. if(eles){
  2208. ruleParser.insertPage(doc, eles, url, callback, true);
  2209. }
  2210. });
  2211. }else{
  2212. isPause=true;
  2213. callback(false);
  2214. }
  2215. },
  2216. onerror: function(e){
  2217. debug(e);
  2218. callback(false);
  2219. },
  2220. ontimeout: function(e){
  2221. debug(e);
  2222. callback(false);
  2223. }
  2224. });
  2225. }
  2226.  
  2227. var failFromIframe=0;
  2228. var inCors=false;
  2229. function requestFromIframe(url, callback){
  2230. url=url.replace(/#[^#]*/,"");
  2231. let orgPage,curPage;
  2232. let iframe = document.createElement('iframe');
  2233. iframe.name = 'pagetual-iframe';
  2234. iframe.width = '100%';
  2235. iframe.height = '0';
  2236. iframe.frameBorder = '0';
  2237. if(ruleParser.curSiteRule.sandbox!=false){
  2238. iframe.sandbox="allow-same-origin allow-scripts allow-popups allow-forms";
  2239. }
  2240. iframe.style.cssText = 'margin:0!important;padding:0!important;visibility:hidden!important;';
  2241. let waitTime=100,checkEval;
  2242. if(ruleParser.curSiteRule.wait){
  2243. if(isNaN(ruleParser.curSiteRule.wait)){
  2244. try{
  2245. checkEval=Function("doc",'"use strict";' + ruleParser.curSiteRule.wait);
  2246. }catch(e){
  2247. debug(e);
  2248. }
  2249. }else{
  2250. waitTime=ruleParser.curSiteRule.wait;
  2251. }
  2252. }
  2253. let loadedHandler=e=>{
  2254. if(e.data != 'pagetual-iframe:DOMLoaded' && e.type != 'load')return;
  2255. window.removeEventListener('message', loadedHandler, false);
  2256. iframe.removeEventListener('load', loadedHandler, false);
  2257. let tryTimes=0;
  2258. function checkIframe(){
  2259. try{
  2260. let doc=iframe.contentDocument || iframe.contentWindow.document;
  2261. let eles=ruleParser.getPageElement(doc, iframe.contentWindow);
  2262. if(eles && eles.length>0 && (!checkEval || checkEval(doc))){
  2263. callback(doc, eles);
  2264. }else if(tryTimes++ < 10){
  2265. setTimeout(()=>{
  2266. checkIframe();
  2267. },waitTime);
  2268. return;
  2269. }else{
  2270. if(failFromIframe++ > 2){
  2271. failFromIframe=0;
  2272. debug("Stop as failFromIframe");
  2273. isPause=true;
  2274. callback(false, false);
  2275. }else{
  2276. callback(false, false);
  2277. }
  2278. }
  2279. }catch(e){
  2280. debug("Stop as cors");
  2281. inCors=true;
  2282. //isPause=true;
  2283. if(!ruleParser.curSiteRule.pageElement){
  2284. ruleParser.curSiteRule.pageElement=allOfBody;
  2285. ruleParser.getInsert(true);
  2286. }
  2287. ruleParser.curSiteRule.action=0;
  2288. ruleParser.nextLinkHref=url;
  2289. callback(false, false);
  2290. nextPage();
  2291. }
  2292. document.body.removeChild(iframe);
  2293. }
  2294. setTimeout(()=>{
  2295. checkIframe();
  2296. },waitTime);
  2297. };
  2298. window.addEventListener('message', loadedHandler, false);
  2299. iframe.addEventListener('load', loadedHandler, false);
  2300. iframe.src=url;
  2301. document.body.appendChild(iframe);
  2302. }
  2303.  
  2304. function initPage(){
  2305. ruleParser.initPage(()=>{
  2306. if(ruleParser.nextLinkHref){
  2307. let isJs=/^(javascript|#)/.test(ruleParser.nextLinkHref.replace(location.href,""));
  2308. if(!isJs){
  2309. let inForce=(forceState == 2 || forceState == 3);
  2310. _GM_registerMenuCommand(i18n(inForce?"cancelForceIframe":"forceIframe"), ()=>{
  2311. if(inForce){
  2312. storage.setItem("forceState_"+location.host, "");
  2313. }else{
  2314. let _state=ruleParser.curSiteRule.action>0 || confirm(i18n("forceAllBody"))?2:3;
  2315. storage.setItem("forceState_"+location.host, _state);
  2316. }
  2317. location.reload();
  2318. });
  2319. }
  2320. _GM_registerMenuCommand(i18n("loadNow"), ()=>{
  2321. let loadNum=window.prompt(i18n("loadConfirm"), "1");
  2322. if(loadNum==="" || loadNum===null)return;
  2323. autoLoadNum=Math.abs(parseInt(loadNum));
  2324. nextPage();
  2325. });
  2326. }
  2327. initListener();
  2328. if(rulesData.initRun && ruleParser.curSiteRule.initRun!=0)nextPage();
  2329. });
  2330. }
  2331.  
  2332. var pageBarStyle;
  2333. function initView(){
  2334. _GM_addStyle(`
  2335. .pagetual_pageBar.stop {
  2336. -webkit-filter: invert(100%);
  2337. filter: invert(100%);
  2338. opacity: 1!important;
  2339. }
  2340. .pagetual_pageBar.hide {
  2341. display: none!important;
  2342. }
  2343. .pagetual_pageBar:hover {
  2344. opacity: 1!important;
  2345. }
  2346. .pagetual_pageBar span {
  2347. vertical-align: super;
  2348. }
  2349.  
  2350. .pagetual_pageBar span>svg:hover {
  2351. animation: touhouAni 1s infinite;
  2352. }
  2353. .pagetual_pageBar .pagetual_pageNum{
  2354. color: #55555f;
  2355. }
  2356. .pagetual_pageBar .pagetual_pageNum:hover{
  2357. color: #ff6464;
  2358. }
  2359. .pagetual_tipsWords{
  2360. font-size: 50px;
  2361. font-weight: bold;
  2362. font-family: "黑体", -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto",
  2363. "Oxygen", "Ubuntu", "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji",
  2364. "Segoe UI Emoji", "Segoe UI Symbol";
  2365. color: #ffffff;
  2366. height: 70px;
  2367. line-height: 70px;
  2368. position: fixed;
  2369. left: 50%;
  2370. top: 10%;
  2371. margin-left: -150px;
  2372. padding: 0 10px;
  2373. z-index: 999999999;
  2374. background-color: #000;
  2375. border: 1px solid black;
  2376. border-radius: 10px;
  2377. opacity: 0;
  2378. filter: alpha(opacity=65);
  2379. box-shadow: 5px 5px 20px 0px #000;
  2380. -moz-transition:opacity 0.3s ease-in-out 0s;
  2381. -webkit-transition:opacity 0.3s ease-in-out 0s;
  2382. transition:opacity 0.3s ease-in-out 0s;
  2383. pointer-events: none;
  2384. }
  2385.  
  2386. @keyframes touhouAni{
  2387. from {transform: rotate(0deg) scale3d(1.2, 1.2, 1.2);}
  2388. to {transform: rotate(360deg);}
  2389. }
  2390. @-webkit-keyframes touhouAni{
  2391. from {transform: rotate(0deg) scale3d(1.2, 1.2, 1.2);}
  2392. to {transform: rotate(360deg);}
  2393. }
  2394. .pagetual_loading {
  2395. width: 50px;
  2396. height: 50px;
  2397. margin: 10px auto;
  2398. border-radius: 100%;
  2399. -webkit-animation: pagetual_loading_scaleout 1.0s infinite ease-in-out;
  2400. animation: pagetual_loading_scaleout 1.0s infinite ease-in-out;
  2401. }
  2402. @-webkit-keyframes pagetual_loading_scaleout {
  2403. 0% { -webkit-transform: scale(0.0) }
  2404. 100% {
  2405. -webkit-transform: scale(1.0);
  2406. opacity: 0;
  2407. }
  2408. }
  2409. @keyframes pagetual_loading_scaleout {
  2410. 0% {
  2411. transform: scale(0.0);
  2412. -webkit-transform: scale(0.0);
  2413. } 100% {
  2414. transform: scale(1.0);
  2415. -webkit-transform: scale(1.0);
  2416. opacity: 0;
  2417. }
  2418. }
  2419. `);
  2420. pageBarStyle=`line-height:1;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%);font-size: 30px;visibility: visible; position: initial; width: auto; height: 30px; float: none; clear: both; margin: 5px auto; text-align: center;`;
  2421. }
  2422. var loadingDiv=document.createElement("div");
  2423. 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;";
  2424. 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><div class="pagetual_loading"><svg width="50" height="50" style="position:relative;cursor: pointer;width: 50px;height: 50px;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="#6e6e6e" 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="#6e6e6e" p-id="6366"></path></svg></div>`;
  2425. var loadingCSS=`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;`;
  2426.  
  2427. var upSvg=`<svg width="30" height="30" style="display:initial;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>`;
  2428. var upSvgCSS=`display:initial;position:absolute;cursor: pointer;margin: 0 -45px;width: 30px;height: 30px;vertical-align: middle;fill: currentColor;overflow: hidden;`;
  2429. var downSvg=`<svg width="30" height="30" style="display:initial;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>`;
  2430. var downSvgCSS=`display:initial;position:absolute;cursor: pointer;margin: 0 15px;width: 30px;height: 30px;vertical-align: middle;fill: currentColor;overflow: hidden;transform: rotate(180deg);`;
  2431.  
  2432. var initStyle=`display: contents;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: relative;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;`;
  2433. var pageTextStyle=`line-height: 30px;text-decoration: none;user-select: none;visibility: visible;position: initial;width: auto;max-width: 80%; white-space: nowrap; text-overflow: ellipsis;overflow: hidden;height: auto;float: none;clear: both;margin: 0px auto;text-align: center;display: inline-block;font-weight: bold;font-style: normal;font-size: 16px;letter-spacing: initial;vertical-align: top;color: rgb(85, 85, 95);`;
  2434.  
  2435. var tipsWords=document.createElement("div");
  2436. tipsWords.className="pagetual_tipsWords";
  2437.  
  2438. var isPause=false,isLoading=false,curPage=1,forceState=0,bottomGap=1000,autoLoadNum=-1;
  2439.  
  2440. function changeStop(stop, hide){
  2441. isPause=stop;
  2442. [].forEach.call(document.querySelectorAll(".pagetual_pageBar"), bar=>{
  2443. if(isPause){
  2444. bar.classList.add("stop");
  2445. if(hide)bar.classList.add("hide");
  2446. }else{
  2447. bar.classList.remove("stop");
  2448. if(hide)bar.classList.remove("hide");
  2449. }
  2450. });
  2451. }
  2452.  
  2453. function isInViewPort(element) {
  2454. if(!element.parentNode)return false;
  2455. if(_unsafeWindow.getComputedStyle(element).display=="none")return false;
  2456. const viewWidth = window.innerWidth || document.documentElement.clientWidth;
  2457. const viewHeight = window.innerHeight || document.documentElement.clientHeight;
  2458. const {
  2459. top,
  2460. right,
  2461. bottom,
  2462. left,
  2463. } = element.getBoundingClientRect();
  2464.  
  2465. return (
  2466. top >= 0 &&
  2467. left >= 0 &&
  2468. right <= viewWidth + 1 &&
  2469. bottom <= viewHeight * 2
  2470. );
  2471. }
  2472.  
  2473. var urlChanged=false;
  2474. var _wr = function(type) {
  2475. var orig = history[type];
  2476. return function() {
  2477. var rv = orig.apply(this, arguments);
  2478. var e = new Event(type);
  2479. e.arguments = arguments;
  2480. window.dispatchEvent(e);
  2481. return rv;
  2482. };
  2483. };
  2484. history.pushState = _wr('pushState');
  2485. window.addEventListener('pushState', function(e) {
  2486. urlChanged=true;
  2487. isPause=true;
  2488. setTimeout(()=>{
  2489. if(location.href==configPage){
  2490. location.reload();
  2491. }
  2492. },1);
  2493. });
  2494.  
  2495. function initListener(){
  2496. let loadmoreBtn,loading=true,lastScroll=0,checkLoadMoreTimes=0;
  2497. let checkLoadMore=setInterval(()=>{
  2498. loadmoreBtn=getLoadMore(document);
  2499. if(loadmoreBtn && isVisible(loadmoreBtn, _unsafeWindow)){
  2500. loading=false;
  2501. clearInterval(checkLoadMore);
  2502. }else if(checkLoadMoreTimes>10){
  2503. clearInterval(checkLoadMore);
  2504. }
  2505. },300);
  2506. let checkScrollReach=()=>{
  2507. let scrolly=window.scrollY;
  2508. let windowHeight=window.innerHeight || document.documentElement.clientHeight;
  2509. let scrollH=Math.max(document.documentElement.scrollHeight, document.body.scrollHeight);
  2510. if(scrollH-scrolly-windowHeight<bottomGap){
  2511. nextPage();
  2512. }
  2513. };
  2514. let scrollHandler = e=>{
  2515. if(urlChanged){
  2516. ruleParser.initPage(()=>{
  2517. if(ruleParser.nextLinkHref)initView();
  2518. });
  2519. urlChanged=false;
  2520. isPause=false;
  2521. }
  2522. if(isPause)return;
  2523. if(!loading){
  2524. if(!loadmoreBtn || !loadmoreBtn.parentNode){
  2525. loadmoreBtn=getLoadMore(document);
  2526. }
  2527. if(loadmoreBtn){
  2528. if(isInViewPort(loadmoreBtn)){
  2529. emuClick(loadmoreBtn);
  2530. loading=true;
  2531. setTimeout(()=>{loading=false},200);
  2532. }
  2533. }else{
  2534. loading=true;
  2535. setTimeout(()=>{loading=false},200);
  2536. }
  2537. }
  2538. if(!isLoading){
  2539. checkScrollReach();
  2540. }
  2541. if(ruleParser.curSiteRule.lockScroll){
  2542. let curScroll=document.body.scrollTop||document.documentElement.scrollTop;
  2543. if(lastScroll!=0 && isLoading && Math.abs(lastScroll-curScroll)>100){
  2544. document.body.scrollTop=lastScroll;
  2545. document.documentElement.scrollTop=lastScroll;
  2546. }else{
  2547. lastScroll=curScroll;
  2548. }
  2549. }
  2550. };
  2551. if(!ruleParser.curSiteRule.wheel){
  2552. document.addEventListener('scroll', scrollHandler, true);
  2553. }
  2554. document.addEventListener('wheel', scrollHandler, true);
  2555. document.addEventListener('dblclick', e=>{
  2556. if(e.target.tagName!="BODY"){
  2557. let selStr=document.getSelection().toString().trim();
  2558. if(selStr){
  2559. return;
  2560. }
  2561. }
  2562. if(rulesData.dbClick2Stop && (ruleParser.nextLinkHref || loadmoreBtn)){
  2563. setTimeout(()=>{
  2564. changeStop(!isPause, rulesData.hideBar);
  2565. if(!isPause){
  2566. checkScrollReach();
  2567. }
  2568. showTips(i18n(isPause?"disable":"enable"));
  2569. },10);
  2570. }
  2571. });
  2572. }
  2573.  
  2574. function showTips(content, wordColor, backColor){
  2575. document.body.appendChild(tipsWords);
  2576. tipsWords.style.opacity=0.8;
  2577. tipsWords.innerText=content;
  2578. tipsWords.style.marginLeft=-tipsWords.offsetWidth/2+"px";
  2579. tipsWords.style.color=wordColor||0xFFFFFF;
  2580. tipsWords.style.backgroundColor=backColor||0x000;
  2581. setTimeout(()=>{tipsWords.style.opacity=0},1000);
  2582. }
  2583.  
  2584. function getLoadMore(doc){
  2585. if(ruleParser.curSiteRule.loadMore==="")return null;
  2586. let btnSel=ruleParser.curSiteRule.loadMore||".LoadMore,.load-more,.button-show-more",loadmoreBtn;
  2587. if(btnSel){
  2588. try{
  2589. loadmoreBtn=doc.querySelector(btnSel);
  2590. }catch(e){
  2591. loadmoreBtn=getElementByXpath(btnSel,doc,doc);
  2592. }
  2593. }
  2594. if(!loadmoreBtn){
  2595. let buttons=doc.querySelectorAll("input,button,a,div[onclick]"),loadmoreReg=/^\s*(加载更多|加載更多|load\s*more|もっと読み込む)\s*$/i;
  2596. for(let i=0;i<buttons.length;i++){
  2597. let button=buttons[i];
  2598. if(button && loadmoreReg.test(button.innerText)){
  2599. loadmoreBtn=button;
  2600. break;
  2601. }
  2602. }
  2603. }
  2604. if(loadmoreBtn && !ruleParser.curSiteRule.loadMore && loadmoreBtn.href && !/^(javascript|#)/.test(loadmoreBtn.href))loadmoreBtn=null;
  2605. return loadmoreBtn;
  2606. }
  2607.  
  2608. var hasPageNum=true;
  2609. function createPageBar(url){
  2610. let insert=ruleParser.getInsert();
  2611. if(!insert || !insert.parentNode)return;
  2612. curPage++;
  2613. let example=ruleParser.curSiteRule.insertPos==2?insert.children[0]:(insert.previousElementSibling||insert);
  2614. if(!example || !example.parentNode)example=insert;
  2615. let inTable=example.parentNode.tagName=="TABLE" ||
  2616. example.tagName=="TR" ||
  2617. example.tagName=="TBODY" ||
  2618. (example.previousElementSibling && example.previousElementSibling.tagName=="TR") ||
  2619. (example.previousElementSibling && example.previousElementSibling.tagName=="TBODY");
  2620. let inLi=example.tagName=="LI" || (example.previousElementSibling && example.previousElementSibling.tagName=="LI");
  2621. if(forceState==2){
  2622. inTable=inLi=false;
  2623. }
  2624. let pageBar=document.createElement(inTable?"tr":(inLi?"li":"div"));
  2625. let upSpan=document.createElement("span");
  2626. let downSpan=document.createElement("span");
  2627. let pageText=document.createElement("a");
  2628. let pageNum;
  2629. pageBar.className="pagetual_pageBar";
  2630. pageBar.id="pagetual_pageBar";
  2631. if(isPause){
  2632. pageBar.classList.add("stop");
  2633. }
  2634. pageBar.style.cssText=pageBarStyle;
  2635. pageBar.title=i18n(isPause?"enable":"disable");
  2636. upSpan.innerHTML=upSvg;
  2637. upSpan.children[0].style.cssText=upSvgCSS;
  2638. upSpan.title=i18n("toTop");
  2639. downSpan.innerHTML=downSvg;
  2640. downSpan.children[0].style.cssText=downSvgCSS;
  2641. downSpan.title=i18n("toBottom");
  2642. upSpan.style.cssText=initStyle;
  2643. downSpan.style.cssText=initStyle;
  2644. pageText.href=url;
  2645. pageText.style.cssText=pageTextStyle;
  2646. pageText.title=i18n("current");
  2647. pageBar.appendChild(upSpan);
  2648. pageBar.appendChild(pageText);
  2649. if(ruleParser.nextTitle){
  2650. pageText.innerHTML=ruleParser.nextTitle+" ";
  2651. pageText.title=ruleParser.nextTitle;
  2652. }
  2653. if(ruleParser.curSiteRule.pageNum || (hasPageNum && /[&\/\?](p=|page[=\/_-]?)\d+|[_-]\d+\./.test(url))){
  2654. pageText.innerHTML+="Page ";
  2655. pageNum=document.createElement("span");
  2656. pageNum.innerText=curPage;
  2657. pageNum.className="pagetual_pageNum";
  2658. pageNum.title=i18n("inputPageNum");
  2659. pageNum.style.cssText=pageTextStyle;
  2660. pageNum.style.cursor="pointer";
  2661. pageNum.style.color="";
  2662. pageNum.style.marginLeft="5px";
  2663. pageNum.addEventListener("click", e=>{
  2664. let pageInput=prompt(i18n("inputPageNum"), "1");
  2665. if(pageInput){
  2666. let pageLink=ruleParser.getLinkByPage(url, pageInput);
  2667. if(pageLink){
  2668. _GM_openInTab(pageLink,{active:true});
  2669. }
  2670. }
  2671. e.preventDefault();
  2672. e.stopPropagation();
  2673. });
  2674. pageBar.appendChild(pageNum);
  2675. }else{
  2676. pageText.innerHTML+="Page "+curPage;
  2677. hasPageNum=false;
  2678. }
  2679. pageBar.appendChild(downSpan);
  2680. let parentStyle=_unsafeWindow.getComputedStyle(example.parentNode);
  2681. let parentWidth=example.parentNode.scrollWidth||parseInt(parentStyle.width);
  2682. pageBar.style.width=parentWidth-parseInt(parentStyle.paddingLeft)-parseInt(parentStyle.paddingRight)-10+"px";
  2683. if(parentStyle.display=="grid" || parentStyle.display=="inline-grid"){
  2684. pageBar.style.gridColumnStart=1;
  2685. pageBar.style.gridColumnEnd=1+parseInt(example.parentNode.offsetWidth/example.offsetWidth);
  2686. }
  2687. if(inTable){
  2688. example=(example.tagName=="TR" || example.tagName=="TBODY")?example:example.previousElementSibling;
  2689. if(example.tagName=="TBODY")example=example.querySelector("tr");
  2690. if(example.previousElementSibling)example=example.previousElementSibling;
  2691. let tdNum=0;
  2692. [].forEach.call(example.children, el=>{
  2693. if(el.tagName=="TD" || el.tagName=="TH"){
  2694. tdNum+=el.colSpan||1;
  2695. }
  2696. });
  2697. pageBar.style.display="table-row";
  2698. pageBar.style.backgroundColor="unset";
  2699. pageBar.style.lineHeight="20px";
  2700. pageBar.style.boxShadow="";
  2701. let td=document.createElement("td");
  2702. td.colSpan=tdNum||1;
  2703. let inTd=document.createElement("div");
  2704. inTd.style.backgroundColor="rgb(240 240 240 / 80%)";
  2705. inTd.style.borderRadius="20px";
  2706. inTd.style.padding="0 0";
  2707. inTd.style.margin="10px";
  2708. inTd.style.lineHeight="20px";
  2709. inTd.style.textAlign="center";
  2710. inTd.style.boxShadow="rgb(0 0 0 / 67%) 0px 0px 10px 0px";
  2711. inTd.appendChild(upSpan);
  2712. inTd.appendChild(pageText);
  2713. if(pageNum)inTd.appendChild(pageNum);
  2714. inTd.appendChild(downSpan);
  2715. td.appendChild(inTd);
  2716. pageBar.appendChild(td);
  2717. }else if(inLi){
  2718. example=example.tagName=="LI"?example:example.previousElementSibling;
  2719. pageBar.style.display="table-row";
  2720. pageBar.style.backgroundColor="unset";
  2721. pageBar.style.lineHeight="20px";
  2722. pageBar.style.boxShadow="";
  2723. let td=document.createElement("td");
  2724. td.colSpan=example.children.length;
  2725. let inTd=document.createElement("div");
  2726. inTd.style.backgroundColor="rgb(240 240 240 / 80%)";
  2727. inTd.style.borderRadius="20px";
  2728. inTd.style.margin="10px"
  2729. inTd.style.padding="0 0";
  2730. inTd.style.textAlign="center";
  2731. inTd.style.minWidth="150px";
  2732. inTd.appendChild(upSpan);
  2733. inTd.appendChild(pageText);
  2734. inTd.style.width=parseInt(pageBar.style.width)-20+"px";
  2735. inTd.style.boxShadow="rgb(0 0 0 / 67%) 0px 0px 10px 0px";
  2736. if(pageNum)inTd.appendChild(pageNum);
  2737. inTd.appendChild(downSpan);
  2738. td.appendChild(inTd);
  2739. pageBar.appendChild(td);
  2740. }
  2741.  
  2742. upSpan.addEventListener("click", e=>{
  2743. document.body.scrollTop=0;
  2744. document.documentElement.scrollTop=0;
  2745. e.preventDefault();
  2746. e.stopPropagation();
  2747. });
  2748. downSpan.addEventListener("click", e=>{
  2749. changeStop(true);
  2750. pageBar.title=i18n(isPause?"enable":"disable");
  2751. document.body.scrollTop=9999999;
  2752. document.documentElement.scrollTop=9999999;
  2753. e.preventDefault();
  2754. e.stopPropagation();
  2755. });
  2756. pageBar.addEventListener("click", e=>{
  2757. changeStop(!isPause);
  2758. pageBar.title=i18n(isPause?"enable":"disable");
  2759. });
  2760. pageText.addEventListener("click", e=>{
  2761. e.stopPropagation();
  2762. });
  2763. if(ruleParser.curSiteRule.insertPos==2){
  2764. insert.appendChild(pageBar);
  2765. }else{
  2766. insert.parentNode.insertBefore(pageBar, insert);
  2767. }
  2768. if(ruleParser.curSiteRule.pageBar){
  2769. try{
  2770. Function("pageBar",'"use strict";' + ruleParser.curSiteRule.pageBar)(pageBar);
  2771. }catch(e){
  2772. debug(e);
  2773. }
  2774. }
  2775.  
  2776. let scrollH=Math.max(document.documentElement.scrollHeight, document.body.scrollHeight);
  2777. let posEle=pageBar.nextElementSibling||pageBar;
  2778. while(posEle && !posEle.offsetParent){
  2779. posEle=posEle.previousElementSibling||posEle.parentNode;
  2780. }
  2781. if(posEle){
  2782. let actualTop = getElementTop(posEle);
  2783. bottomGap=scrollH-actualTop+(window.innerHeight||document.documentElement.clientHeight)*(ruleParser.curSiteRule.rate||1);
  2784. if(bottomGap<100)bottomGap=100;
  2785. }else{
  2786. bottomGap=1000;
  2787. }
  2788. if(rulesData.opacity==0)pageBar.style.display="none";
  2789. return pageBar;
  2790. }
  2791.  
  2792. function emuClick(btn){
  2793. if(!PointerEvent)return btn.click();
  2794. let eventParam={
  2795. isTrusted: true,
  2796. altKey: false,
  2797. azimuthAngle: 0,
  2798. bubbles: true,
  2799. button: 0,
  2800. buttons: 0,
  2801. clientX: 1,
  2802. clientY: 1,
  2803. cancelBubble: false,
  2804. cancelable: true,
  2805. composed: true,
  2806. ctrlKey: false,
  2807. defaultPrevented: false,
  2808. detail: 1,
  2809. eventPhase: 2,
  2810. fromElement: null,
  2811. height: 1,
  2812. isPrimary: false,
  2813. metaKey: false,
  2814. pointerId: 1,
  2815. pointerType: "mouse",
  2816. pressure: 0,
  2817. relatedTarget: null,
  2818. returnValue: true,
  2819. shiftKey: false,
  2820. toElement: null,
  2821. twist: 0,
  2822. which: 1
  2823. };
  2824. var mouseEvent = new PointerEvent("mousedown",eventParam);
  2825. btn.dispatchEvent(mouseEvent);
  2826. mouseEvent = new PointerEvent("mouseup",eventParam);
  2827. btn.dispatchEvent(mouseEvent);
  2828. btn.click();
  2829. }
  2830.  
  2831. var emuIframe;
  2832. function emuPage(callback){
  2833. let orgPage=null,curPage,iframeDoc,times=0,loadmoreBtn,loadmoreEnd=false,waitTimes=10,changed=false;
  2834. function checkPage(){
  2835. if(isPause)return;
  2836. try{
  2837. iframeDoc=emuIframe.contentDocument || emuIframe.contentWindow.document;
  2838. }catch(e){
  2839. debug("Stop as cors");
  2840. isPause=true;
  2841. callback(false, false);
  2842. return;
  2843. }
  2844.  
  2845. let nextLink=ruleParser.getNextLink(iframeDoc);
  2846. let waitTime=200,checkEval;
  2847. if(ruleParser.curSiteRule.wait){
  2848. if(isNaN(ruleParser.curSiteRule.wait)){
  2849. try{
  2850. checkEval=Function("doc",'"use strict";' + ruleParser.curSiteRule.wait);
  2851. }catch(e){
  2852. debug(e);
  2853. }
  2854. }else{
  2855. waitTime=ruleParser.curSiteRule.wait;
  2856. }
  2857. }
  2858.  
  2859. if(!orgPage){
  2860. if(!loadmoreEnd){
  2861. loadmoreBtn=getLoadMore(iframeDoc);
  2862. if(loadmoreBtn && isVisible(loadmoreBtn, iframeDoc.defaultView)){
  2863. emuClick(loadmoreBtn);
  2864. let intv=setInterval(()=>{
  2865. loadmoreBtn=getLoadMore(iframeDoc);
  2866. if(!loadmoreBtn || !loadmoreBtn.parentNode || !isVisible(loadmoreBtn, iframeDoc.defaultView)){
  2867. clearInterval(intv);
  2868. loadmoreEnd=true;
  2869. setTimeout(()=>{
  2870. checkPage();
  2871. },500);
  2872. }else{
  2873. emuClick(loadmoreBtn);
  2874. }
  2875. },200);
  2876. return;
  2877. }else{
  2878. loadmoreEnd=true;
  2879. }
  2880. }
  2881. let pageEle=ruleParser.getPageElement(iframeDoc, iframeDoc.defaultView, true);
  2882. if(!nextLink || !pageEle || pageEle.length==0 || (checkEval && !checkEval(iframeDoc))){
  2883. if(waitTimes-->0){
  2884. setTimeout(()=>{
  2885. checkPage();
  2886. },waitTime);
  2887. return;
  2888. }
  2889. }
  2890. orgPage=pageEle;
  2891. if(!orgPage || orgPage.length==0){
  2892. debug("Stop as no page when emu");
  2893. isPause=true;
  2894. callback(false, false);
  2895. return;
  2896. }
  2897. if(orgPage && orgPage[0].tagName=="UL")orgPage=orgPage[0].children;
  2898. if(orgPage && nextLink){
  2899. orgPage=orgPage[parseInt(orgPage.length/2)];
  2900. if(!isVisible(nextLink, iframeDoc.defaultView)){
  2901. debug("Stop as next hide when emu");
  2902. isPause=true;
  2903. callback(false, false);
  2904. }else{
  2905. emuClick(nextLink);
  2906. setTimeout(()=>{
  2907. checkPage();
  2908. },500);
  2909. }
  2910. }else{
  2911. debug("Stop as no next when emu");
  2912. isPause=true;
  2913. callback(false, false);
  2914. }
  2915. return;
  2916. }
  2917. if(times++ > 20){
  2918. debug("Stop as timeout when emu");
  2919. isPause=true;
  2920. callback(false, false);
  2921. return;
  2922. }
  2923. let eles=ruleParser.getPageElement(iframeDoc, iframeDoc.defaultView, true),checkItem;
  2924. if(eles && eles.length>0){
  2925. checkItem=eles;
  2926. if(eles[0].tagName=="UL"){
  2927. checkItem=eles[0].children;
  2928. }
  2929. checkItem=checkItem[parseInt(checkItem.length/2)];
  2930. }
  2931. if(!checkItem || (checkEval && !checkEval(iframeDoc))){
  2932. setTimeout(()=>{
  2933. checkPage();
  2934. },waitTime);
  2935. }else{
  2936. if(orgPage!=checkItem){
  2937. changed=true;
  2938. orgPage=checkItem;
  2939. setTimeout(()=>{
  2940. checkPage();
  2941. },waitTime);
  2942. }else if(changed){
  2943. callback(iframeDoc, eles);
  2944. }
  2945. }
  2946. }
  2947. if(!emuIframe){
  2948. let loaded=false;
  2949. emuIframe = document.createElement('iframe');
  2950. emuIframe.name = 'pagetual-iframe';
  2951. if(ruleParser.curSiteRule.sandbox!=false){
  2952. emuIframe.sandbox="allow-same-origin allow-scripts allow-popups allow-forms";
  2953. }
  2954. emuIframe.width = '100%';
  2955. emuIframe.height = '0';
  2956. emuIframe.frameBorder = '0';
  2957. emuIframe.style.cssText = 'margin:0!important;padding:0!important;visibility:hidden!important;';
  2958. emuIframe.addEventListener("load", e=>{
  2959. setTimeout(()=>{
  2960. try{
  2961. iframeDoc=emuIframe.contentDocument || emuIframe.contentWindow.document;
  2962. }catch(e){
  2963. debug("Stop as cors");
  2964. isPause=true;
  2965. callback(false, false);
  2966. return;
  2967. }
  2968. let code=ruleParser.curSiteRule.init;
  2969. if(code){
  2970. try{
  2971. Function('doc','win','iframe','"use strict";' + code)(iframeDoc, iframeDoc.defaultView, emuIframe);
  2972. }catch(e){
  2973. debug(e);
  2974. }
  2975. }
  2976. if(loaded)return;
  2977. loaded=true;
  2978. checkPage();
  2979. },500);
  2980. });
  2981. emuIframe.src=location.href.replace(/#[^#]*/,"");
  2982. document.body.appendChild(emuIframe);
  2983. }else{
  2984. checkPage();
  2985. }
  2986. }
  2987.  
  2988. var scrollToResizeInited = false;
  2989. var resizePool = [];
  2990. function scrollToResize() {
  2991. if (scrollToResizeInited) return;
  2992. scrollToResizeInited = true;
  2993. var scrollingToResize = false;
  2994. document.addEventListener("scroll", e => {
  2995. if (scrollingToResize) return;
  2996. else {
  2997. scrollingToResize = true;
  2998. setTimeout(() => {scrollingToResize = false}, 500);
  2999. }
  3000. resizePool.forEach(resizeArr => {
  3001. let iframe = resizeArr[1]();
  3002. let frameDoc = resizeArr[2]();
  3003. if(ruleParser.curSiteRule.singleUrl){
  3004. iframe.style.height=frameDoc.body.scrollHeight+"px";
  3005. iframe.style.width=frameDoc.body.scrollWidth+"px";
  3006. }else{
  3007. let pageEle = resizeArr[0]();
  3008. if(pageEle){
  3009. let targetElement = pageEle[0];
  3010. if(pageEle.length > 1){
  3011. targetElement = targetElement.parentNode;
  3012. }
  3013. iframe.style.height=targetElement.scrollHeight+"px";
  3014. frameDoc.documentElement.scrollTop = 0;
  3015. frameDoc.documentElement.scrollLeft = 0;
  3016. while(targetElement && targetElement.offsetParent){
  3017. targetElement.offsetParent.scrollTop = targetElement.offsetTop;
  3018. if(targetElement.offsetParent.scrollTop == 0){
  3019. frameDoc.documentElement.scrollTop += targetElement.offsetTop;
  3020. }
  3021. targetElement.offsetParent.scrollLeft = targetElement.offsetLeft;
  3022. if(targetElement.offsetParent.scrollLeft == 0){
  3023. frameDoc.documentElement.scrollLeft += targetElement.offsetLeft;
  3024. }
  3025. targetElement = targetElement.offsetParent;
  3026. }
  3027. }
  3028. }
  3029. });
  3030. });
  3031. }
  3032.  
  3033. function forceIframe(url, callback){
  3034. url=url.replace(/#[^#]*/,"");
  3035. let curIframe = document.createElement('iframe'),iframeDoc;
  3036. let setPosition = ()=>{
  3037. let getIframe = () => {
  3038. return curIframe;
  3039. };
  3040. let getFrameDoc = () => {
  3041. return iframeDoc;
  3042. };
  3043. if(ruleParser.curSiteRule.singleUrl){
  3044. resizePool.push([() => {}, getIframe, getFrameDoc]);
  3045. }else{
  3046. let pageElement = ruleParser.getPageElement(iframeDoc,iframeDoc.defaultView);
  3047. let getPageEle = () => {
  3048. if (!pageElement) {
  3049. pageElement = ruleParser.getPageElement(iframeDoc,iframeDoc.defaultView);
  3050. }
  3051. return pageElement;
  3052. };
  3053. resizePool.push([getPageEle, getIframe, getFrameDoc]);
  3054. }
  3055. };
  3056. curIframe.name = 'pagetual-iframe';
  3057. curIframe.sandbox="allow-same-origin allow-scripts allow-popups allow-forms";
  3058. curIframe.frameBorder = '0';
  3059. curIframe.scrolling="no";
  3060. 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;';
  3061. curIframe.addEventListener("load", e=>{
  3062. try{
  3063. iframeDoc=curIframe.contentDocument || curIframe.contentWindow.document;
  3064. }catch(e){
  3065. debug("Stop as cors");
  3066. isPause=true;
  3067. callback(false, false);
  3068. return;
  3069. }
  3070. ruleParser.insertPage(iframeDoc, [], url, null, true);
  3071. callback(curIframe, true);
  3072. let css=ruleParser.curSiteRule.css;
  3073. if(css){
  3074. let styleEle=iframeDoc.createElement("style");
  3075. styleEle.innerHTML=css;
  3076. iframeDoc.head.appendChild(styleEle);
  3077. }
  3078. setPosition();
  3079. let code=ruleParser.curSiteRule.init;
  3080. if(code){
  3081. try{
  3082. Function('doc','win','iframe','"use strict";' + code)(iframeDoc,iframeDoc.defaultView,curIframe);
  3083. }catch(e){
  3084. debug(e);
  3085. }
  3086. }
  3087. });
  3088. let inAction=false,checkTimes=0;
  3089. let forceRefresh=e=>{
  3090. if(inAction || !iframeDoc)return;
  3091. inAction=true;
  3092. let foundNext=()=>{
  3093. document.removeEventListener("scroll", forceRefresh);
  3094. }
  3095. setTimeout(()=>{
  3096. inAction=false;
  3097. if(!ruleParser.nextLinkHref){
  3098. checkTimes++;
  3099. ruleParser.getNextLink(iframeDoc);
  3100. if(ruleParser.nextLinkHref){
  3101. foundNext();
  3102. }else if(checkTimes>=10){
  3103. foundNext();
  3104. }
  3105. }else{
  3106. foundNext();
  3107. }
  3108. },50);
  3109. };
  3110. document.addEventListener("scroll", forceRefresh);
  3111. curIframe.src=url;
  3112. let insert=ruleParser.getInsert();
  3113. if(ruleParser.curSiteRule.singleUrl){
  3114. document.body.appendChild(curIframe);
  3115. }else if(ruleParser.curSiteRule.insertPos==2){
  3116. ruleParser.insert.appendChild(curIframe);
  3117. }else{
  3118. ruleParser.insert.parentNode.insertBefore(curIframe, ruleParser.insert);
  3119. }
  3120. scrollToResize();
  3121. return curIframe;
  3122. }
  3123.  
  3124. function loadPageOver(){
  3125. isLoading=false;
  3126. if(loadingDiv.parentNode){
  3127. loadingDiv.parentNode.removeChild(loadingDiv);
  3128. }
  3129. /*setTimeout(()=>{
  3130. let scrollH=Math.max(document.documentElement.scrollHeight, document.body.scrollHeight);
  3131. if(scrollH <= (window.innerHeight || document.documentElement.clientHeight)){
  3132. nextPage();
  3133. }
  3134. },1);*/
  3135. }
  3136.  
  3137. var tryTimes = 0;
  3138.  
  3139. function nextPage(){
  3140. if(isPause || isLoading)return;
  3141. if(ruleParser.curSiteRule.delay){
  3142. try{
  3143. let checkDelay=Function('"use strict";' + ruleParser.curSiteRule.delay)();
  3144. if(!checkDelay)return;
  3145. }catch(e){
  3146. debug(e);
  3147. }
  3148. }
  3149. let nextLink=ruleParser.nextLinkHref;
  3150. if(!nextLink){
  3151. if(curPage==1){
  3152. ruleParser.getNextLink(document);
  3153. nextLink=ruleParser.nextLinkHref;
  3154. }
  3155. if(!nextLink){
  3156. isPause=true;
  3157. if(curPage==1 && (ruleParser.curSiteRule.pinUrl || tryTimes++ <= 10)){
  3158. setTimeout(()=>{isPause=false},500);
  3159. }
  3160. return;
  3161. }
  3162. }
  3163. let pvGallery=document.querySelector("span.pv-gallery-container");
  3164. if(pvGallery && pvGallery.style.display!="none")return;
  3165. let insert=ruleParser.getInsert();
  3166. if(insert){
  3167. let isJs=/^(javascript|#)/.test(nextLink.replace(location.href,""));
  3168. if(location.protocol=="https:" && /^http:/.test(nextLink)){
  3169. nextLink=nextLink.replace(/^http/,"https");
  3170. }
  3171. isLoading=true;
  3172. document.body.appendChild(loadingDiv);
  3173. loadingDiv.style.cssText=loadingCSS;
  3174. let sleep=ruleParser.curSiteRule.sleep||0;
  3175. setTimeout(()=>{
  3176. if(ruleParser.curSiteRule.pageElementByJs){
  3177. var over=ele=>{
  3178. loadPageOver();
  3179. if(ele){
  3180. createPageBar(nextLink);
  3181. ruleParser.insertPage(null, ele, nextLink, null, true);
  3182. if(autoLoadNum>=0){
  3183. if(autoLoadNum!=0 && --autoLoadNum==0){
  3184. autoLoadNum=-1;
  3185. }else{
  3186. nextPage();
  3187. }
  3188. }
  3189. }else{
  3190. debug("Stop as no page when get by js");
  3191. isPause=true;
  3192. }
  3193. };
  3194. try{
  3195. Function("over",'"use strict";' + ruleParser.curSiteRule.pageElementByJs)(over);
  3196. }catch(e){
  3197. debug(e);
  3198. }
  3199. }else if((forceState==3||ruleParser.curSiteRule.action==1) && !isJs){
  3200. requestFromIframe(nextLink, (doc, eles)=>{
  3201. loadPageOver();
  3202. if(eles){
  3203. createPageBar(nextLink);
  3204. ruleParser.insertPage(doc, eles, nextLink, null, true);
  3205. if(autoLoadNum>=0){
  3206. if(autoLoadNum!=0 && --autoLoadNum==0){
  3207. autoLoadNum=-1;
  3208. }else{
  3209. nextPage();
  3210. }
  3211. }
  3212. }
  3213. });
  3214. }else if((forceState==2||ruleParser.curSiteRule.action==2) && !isJs){
  3215. forceIframe(nextLink, (iframe, eles)=>{
  3216. loadPageOver();
  3217. let pageBar=createPageBar(nextLink);
  3218. if(pageBar)iframe.parentNode.insertBefore(pageBar, iframe);
  3219. if(autoLoadNum>=0){
  3220. if(autoLoadNum!=0 && --autoLoadNum==0){
  3221. autoLoadNum=-1;
  3222. }else{
  3223. nextPage();
  3224. }
  3225. }
  3226. });
  3227. }else{
  3228. if(!isJs){
  3229. requestDoc(nextLink, (eles)=>{
  3230. loadPageOver();
  3231. if(eles){
  3232. createPageBar(nextLink);
  3233. if(autoLoadNum>=0){
  3234. if(autoLoadNum!=0 && --autoLoadNum==0){
  3235. autoLoadNum=-1;
  3236. }else{
  3237. nextPage();
  3238. }
  3239. }
  3240. }
  3241. });
  3242. }else{
  3243. emuPage((doc, eles)=>{
  3244. loadPageOver();
  3245. if(eles){
  3246. createPageBar(nextLink);
  3247. ruleParser.insertPage(doc, eles, "", null, true);
  3248. if(autoLoadNum>=0){
  3249. if(autoLoadNum!=0 && --autoLoadNum==0){
  3250. autoLoadNum=-1;
  3251. }else{
  3252. nextPage();
  3253. }
  3254. }
  3255. }
  3256. });
  3257. }
  3258. }
  3259. },sleep);
  3260. }
  3261. }
  3262.  
  3263. function init(){
  3264. initRules(()=>{
  3265. initPage();
  3266. });
  3267. }
  3268. setTimeout(()=>{
  3269. init();
  3270. },100);
  3271. })();