东方永页机

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

目前为 2022-05-28 提交的版本。查看 最新版本

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