東方永頁機

自動翻頁 - 加載並拼接下一分頁內容至當前頁尾,無需規則自動適配任意網頁

目前為 2022-11-21 提交的版本,檢視 最新版本

  1. // ==UserScript==
  2. // @name Pagetual
  3. // @name:zh-CN 东方永页机
  4. // @name:zh-TW 東方永頁機
  5. // @name:ja 東方永頁機
  6. // @name:ru Pagetual
  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.33.2
  14. // @description Perpetual pages - Most powerful auto-pager script. Auto loading next paginated web pages and inserting into current page. Support thousands of web sites without any rule.
  15. // @description:zh-CN 自动翻页 - 加载并拼接下一分页内容至当前页尾,无需规则自动适配任意网页
  16. // @description:zh-TW 自動翻頁 - 加載並拼接下一分頁內容至當前頁尾,無需規則自動適配任意網頁
  17. // @description:ja Webページを自動で読み込み継ぎ足し表示を行うブラウザ拡張です、次のページ付けされた Web ページの自動読み込みと現在のページへの挿入 ルールなしで何千もの Web サイトをサポートします。
  18. // @description:ru Автоматическая загрузка следующих веб-страниц с разбивкой на страницы и вставка на текущую страницу. Поддержка тысяч веб-сайтов без каких-либо правил.
  19. // @description:de Automatisches Laden der nächsten paginierten Webseiten und Einfügen in die aktuelle Seite. Unterstützen Sie Tausende von Websites ohne Regeln.
  20. // @description:es Carga automática de las siguientes páginas web paginadas e inserción en la página actual. Admite miles de sitios web sin ninguna regla.
  21. // @description:fr Chargement automatique des pages Web paginées suivantes et insertion dans la page en cours. Prend en charge des milliers de sites Web sans aucune règle.
  22. // @description:it Caricamento automatico delle pagine Web impaginate successive e inserimento nella pagina corrente. Supporta migliaia di siti web senza alcuna regola.
  23. // @description:ko 페이지가 매겨진 다음 웹 페이지를 자동으로 로드하고 현재 페이지에 삽입합니다. 규칙 없이 수천 개의 웹 사이트를 지원합니다.
  24. // @author hoothin
  25. // @match *://*/*
  26. // @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==
  27. // @grant GM_xmlhttpRequest
  28. // @grant GM_registerMenuCommand
  29. // @grant GM_notification
  30. // @grant GM_getValue
  31. // @grant GM_setValue
  32. // @grant GM_addStyle
  33. // @grant GM_openInTab
  34. // @grant GM_deleteValue
  35. // @grant GM_info
  36. // @grant GM_setClipboard
  37. // @grant GM.xmlHttpRequest
  38. // @grant GM.registerMenuCommand
  39. // @grant GM.notification
  40. // @grant GM.getValue
  41. // @grant GM.setValue
  42. // @grant GM.addStyle
  43. // @grant GM.openInTab
  44. // @grant GM.deleteValue
  45. // @grant GM.info
  46. // @grant GM.setClipboard
  47. // @supportURL https://github.com/hoothin/UserScripts/issues
  48. // @connect wedata.net
  49. // @connect githubusercontent.com
  50. // @connect ghproxy.com
  51. // @connect hoothin.github.io
  52. // @run-at document-idle
  53. // @exclude http://www.toodledo.com/tasks/*
  54. // @exclude http*://maps.google.com*/*
  55. // @exclude *://www.google.*/_/chrome/newtab*
  56. // @exclude *://mega.*/*
  57. // @exclude *://*.mega.*/*
  58. // @exclude *://*.youku.com/v_*
  59. // @exclude *://*pan.baidu.com
  60. // @exclude *://*.iqiyi.com/v_*
  61. // @exclude *://*.iqiyi.com/w_*
  62. // @exclude *://*.iqiyi.com/a_*
  63. // @exclude *://*.le.com/ptv/vplay/*
  64. // @exclude *://v.qq.com/x/cover/*
  65. // @exclude *://v.qq.com/x/page/*
  66. // @exclude *://v.qq.com/tv/*
  67. // @exclude *://*.tudou.com/listplay/*
  68. // @exclude *://*.tudou.com/albumplay/*
  69. // @exclude *://*.tudou.com/programs/view/*
  70. // @exclude *://*.mgtv.com/b/*
  71. // @exclude *://film.sohu.com/album/*
  72. // @exclude *://tv.sohu.com/v/*
  73. // @exclude *://*.bilibili.com/video/*
  74. // @exclude *://*.bilibili.com/bangumi/play/*
  75. // @exclude *://*.baofeng.com/play/*
  76. // @exclude *://vip.pptv.com/show/*
  77. // @exclude *://v.pptv.com/show/*
  78. // @exclude *://www.le.com/ptv/vplay/*
  79. // @exclude *://www.wasu.cn/Play/show/*
  80. // @exclude *://m.v.qq.com/*
  81. // @exclude *://m.iqiyi.com/*
  82. // @exclude *://m.youku.com/alipay_video/*
  83. // @exclude *://m.mgtv.com/b/*
  84. // @exclude *://m.tv.sohu.com/v/*
  85. // @exclude *://m.film.sohu.com/album/*
  86. // @exclude *://m.le.com/ptv/vplay/*
  87. // @exclude *://m.pptv.com/show/*
  88. // @exclude *://m.acfun.cn/v/*
  89. // @exclude *://m.bilibili.com/video/*
  90. // @exclude *://m.bilibili.com/anime/*
  91. // @exclude *://m.bilibili.com/bangumi/play/*
  92. // @exclude *://m.wasu.cn/Play/show/*
  93. // @exclude *://www.youtube.com
  94. // @exclude *://www.youtube.com/*
  95. // @exclude *://twitter.com/*
  96. // @exclude *://www.youtube.com/watch*
  97. // @exclude *://baike.baidu.com/*
  98. // @exclude *://*.instagram.com/*
  99. // @exclude *://order.jd.com/*
  100. // @exclude *://pagetual.hoothin.com/*
  101. // @exclude *://wenku.baidu.com/view/*
  102. // @exclude *://pan.baidu.com/*
  103. // @connect *
  104. // ==/UserScript==
  105.  
  106. (function() {
  107. 'use strict';
  108.  
  109. if (window.name === 'pagetual-iframe' || (window.frameElement && window.frameElement.name === 'pagetual-iframe')) {
  110. var domloaded = function (){
  111. window.scroll(window.scrollX, 999999);
  112. window.parent.postMessage('pagetual-iframe:DOMLoaded', '*');
  113. };
  114. if(window.opera){
  115. document.addEventListener('DOMContentLoaded', domloaded, false);
  116. } else {
  117. domloaded();
  118. }
  119. if (getComputedStyle(document.documentElement).display == 'none') document.documentElement.style.display = 'block';
  120. if (getComputedStyle(document.body).display == 'none') document.body.style.display = 'block';
  121. return;
  122. }
  123.  
  124. if(window.top != window.self){
  125. try{
  126. if (top.location.hostname != window.location.hostname || window.top != window.parent) {
  127. return;
  128. }
  129. }catch(e){
  130. return;
  131. }
  132. }
  133.  
  134. const noRuleTest = false;
  135. const lang = navigator.appName=="Netscape"?navigator.language:navigator.userLanguage;
  136. let config={};
  137. switch (lang){
  138. case "zh-CN":
  139. case "zh-SG":
  140. config = {
  141. enableDebug:"调试模式,输出信息至控制台",
  142. disable:"暂时禁用",
  143. disableSite:"切换禁用状态",
  144. disableSiteTips:"已在此站禁用",
  145. enableSiteTips:"已在此站启用",
  146. enable:"启用翻页",
  147. toTop:"回到顶部",
  148. toBottom:"前往页尾",
  149. current:"当前页",
  150. forceIframe:"强制拼接",
  151. cancelForceIframe:"取消强制拼接",
  152. configure:"打开配置页面",
  153. firstUpdate:"点击此处初始化规则",
  154. update:"更新规则",
  155. click2update:"点击立即更新规则",
  156. loadNow:"立即翻页",
  157. loadConfirm:"要翻几页?(0为不间断)",
  158. noNext:"没有找到下一页,请新建规则",
  159. passSec:"更新于 #t# 秒前",
  160. passMin:"更新于 #t# 分钟前",
  161. passHour:"更新于 #t# 小时前",
  162. passDay:"更新于 #t# 天前",
  163. cantDel:"无法删除内置规则",
  164. confirmDel:"是否确认要删除此规则?",
  165. updateSucc:"更新成功",
  166. beginUpdate:"正在更新,请耐心等待,不要关闭页面",
  167. customUrls:"导入 Pagetual 或 AutoPagerize 规则 url,一行一条",
  168. customRules:"输入【东方永页机】格式的自定义规则",
  169. save:"保存设置",
  170. loadingText:"少女祈祷中...",
  171. opacity:"不透明值",
  172. opacityPlaceholder:"0: 隐藏分隔条",
  173. hideBar:"隐藏分页隔条",
  174. hideBarButNoStop:"隐藏但不停止",
  175. dbClick2Stop:"空白处双击暂停翻页",
  176. sortTitle:"排序在下次更新规则后生效",
  177. autoRun:"自动启用,否则为白名单模式",
  178. autoLoadNum:"自动加载指定页数",
  179. inputPageNum:"输入页码跳转",
  180. enableHistory:"翻页后写入历史记录",
  181. enableHistoryAfterInsert:"拼接后立即写入历史记录,否则浏览完毕后再行写入",
  182. initRun:"打开页面后立即尝试翻页,否则滚动至页尾再翻页",
  183. preload:"翻页前预读下一页,加速浏览",
  184. click2ImportRule:"点击下方添加特殊规则库,并静待更新成功:",
  185. forceAllBody:"是否拼接整个页面?",
  186. openInNewTab:"使拼接页面的内容在新页面打开",
  187. importSucc:"导入成功",
  188. import:"导入",
  189. editCurrent:"编辑此站规则",
  190. editBlacklist:"编辑黑名单网址,一行一条,支持? *通配符",
  191. upBtnImg:"回到页首图标",
  192. downBtnImg:"前往页尾图标",
  193. loadingTextTitle:"加载中文字",
  194. dbClick2StopCtrl:"Ctrl 键",
  195. dbClick2StopAlt:"Alt 键",
  196. dbClick2StopShift:"Shift 键",
  197. dbClick2StopMeta:"Meta 键",
  198. dbClick2StopKey:"快捷键",
  199. pageElementCss:"页面主体框架的样式",
  200. customCss:"自定义 CSS",
  201. firstAlert:"你还未导入规则库,请选择合适的规则库导入哦",
  202. picker:"东方永页机主体元素抓取器",
  203. closePicker:"关闭东方永页机抓取器",
  204. pickerPlaceholder:"没想法建议留空",
  205. pickerCheck:"检查你编辑的选择器并复制",
  206. switchSelector:"点击切换元素",
  207. gotoEdit:"使用当前的选择器前往编辑规则",
  208. manualMode:"禁用拼接,手动用右方向键翻页,可使用 Alt + 左方向键返回",
  209. clickMode:"禁用拼接,滚动至页尾时自动点击下一页",
  210. pageBarMenu:"点击分隔条中间弹出菜单",
  211. nextSwitch:"切换其他页码",
  212. arrowToScroll:"左方向键滚动至上一页,右方向键滚动至下一页",
  213. hideLoadingIcon:"隐藏加载动画",
  214. duplicate:"检测到永页机重复安装,请删除其他脚本管理器中的永页机!",
  215. forceStateIframe:"以 iframe 嵌入整页",
  216. forceStateDynamic:"通过 iframe 加载动态内容后取出",
  217. forceStateDisable:"在此站禁用"
  218. };
  219. break;
  220. case "zh-TW":
  221. case "zh-HK":
  222. config = {
  223. enableDebug:"調試模式,輸出信息至控制台",
  224. disable:"暫時禁用",
  225. disableSite:"切換禁用狀態",
  226. disableSiteTips:"已在此站禁用",
  227. enableSiteTips:"已在此站啟用",
  228. enable:"啟用翻頁",
  229. toTop:"回到頂部",
  230. toBottom:"前往頁尾",
  231. current:"當前頁",
  232. forceIframe:"強制拼接",
  233. cancelForceIframe:"取消强制拼接",
  234. configure:"打開配置頁面",
  235. firstUpdate:"點擊此處初始化規則",
  236. update:"更新規則",
  237. click2update:"點擊立即更新規則",
  238. loadNow:"立即翻頁",
  239. loadConfirm:"要翻几頁?(0為不間斷)",
  240. noNext:"沒有找到下一頁,請新建規則",
  241. passSec:"更新于 #t# 秒前",
  242. passMin:"更新于 #t# 分鐘前",
  243. passHour:"更新于 #t# 小時前",
  244. passDay:"更新于 #t# 天前",
  245. cantDel:"無法刪除内置規則",
  246. confirmDel:"是否確認要刪除此規則?",
  247. updateSucc:"更新成功",
  248. beginUpdate:"正在更新,請稍候",
  249. customUrls:"導入 Pagetual 或 AutoPagerize 規則 url,一行一條",
  250. customRules:"輸入【東方永頁機】格式的自定義規則",
  251. save:"存儲設置",
  252. loadingText:"少女祈禱中...",
  253. opacity:"不透明值",
  254. opacityPlaceholder:"0: 隱藏分隔條",
  255. hideBar:"隱藏分頁隔條",
  256. hideBarButNoStop:"隱藏但不停止",
  257. dbClick2Stop:"空白處雙擊暫停翻頁",
  258. sortTitle:"排序在下次更新規則後生效",
  259. autoRun:"自動啓用,否則為白名單模式",
  260. autoLoadNum:"自動加載指定頁數",
  261. inputPageNum:"輸入頁碼跳轉",
  262. enableHistory:"翻頁后寫入歷史記錄",
  263. enableHistoryAfterInsert:"拼接後立即寫入歷史記錄,否則瀏覽完畢後再行寫入",
  264. initRun:"打開頁面后立即嘗試翻頁,否則滾動至頁尾再翻頁",
  265. preload:"翻頁前預讀下一頁,加速瀏覽",
  266. click2ImportRule:"點擊下方添加特殊規則庫,并靜待更新成功:",
  267. forceAllBody:"是否拼接整個頁面?",
  268. openInNewTab:"使拼接頁面的内容在新頁面打開",
  269. importSucc:"導入成功",
  270. import:"導入",
  271. editCurrent:"編輯此站規則",
  272. editBlacklist:"編輯黑名單網址,一行一條,支持? *通配符",
  273. upBtnImg:"回到頁首圖標",
  274. downBtnImg:"前往頁尾圖標",
  275. loadingTextTitle:"加載中文字",
  276. dbClick2StopCtrl:"Ctrl 鍵",
  277. dbClick2StopAlt:"Alt 鍵",
  278. dbClick2StopShift:"Shift 鍵",
  279. dbClick2StopMeta:"Meta 鍵",
  280. dbClick2StopKey:"快捷鍵",
  281. pageElementCss:"頁面主體框架的樣式",
  282. customCss:"自定義 CSS",
  283. firstAlert:"你還未導入規則庫,請選擇合適的規則庫導入哦",
  284. picker:"東方永頁機主體元素抓取器",
  285. closePicker:"關閉東方永頁機抓取器",
  286. pickerPlaceholder:"沒想法建議留空",
  287. pickerCheck:"檢查你編輯的選擇器並複製",
  288. switchSelector:"點擊切換元素",
  289. gotoEdit:"使用當前的選擇器前往編輯規則",
  290. manualMode:"禁用拼接,手動用右方向鍵翻頁",
  291. clickMode:"禁用拼接,滾動至頁尾時自動點擊下一頁",
  292. pageBarMenu:"點擊分隔條中間彈出菜單",
  293. nextSwitch:"切換其他頁碼",
  294. arrowToScroll:"左方向鍵滾動至上一頁,右方向鍵滾動至下一頁",
  295. hideLoadingIcon:"隱藏加載動畫",
  296. duplicate:"檢測到永頁機重複安裝,請刪除其他腳本管理器中的永頁機!",
  297. forceStateIframe:"以 iframe 嵌入整頁",
  298. forceStateDynamic:"通過 iframe 加載動態內容後取出",
  299. forceStateDisable:"在此站禁用"
  300. };
  301. break;
  302. case "ja":
  303. config = {
  304. enableDebug:"デバッグモード",
  305. disable: "一時的に無効にする",
  306. disableSite:"無効状態の切り替え",
  307. disableSiteTips:"このサイトで既に無効になっています",
  308. enableSiteTips:"このサイトで既に有効になっています",
  309. enable: "ページめくりを有効にする",
  310. toTop: "トップに戻る",
  311. toBottom: "ページの下部に移動",
  312. current: "現在のページ",
  313. forceIframe: "強制ステッチ",
  314. cancelForceIframe: "強制ステッチをキャンセル",
  315. configure: "設定ページを開く",
  316. firstUpdate:"ここをクリックしてルールを初期化します",
  317. update: "更新ルール",
  318. click2update:"今すぐルールを更新してください",
  319. loadNow:"今すぐページをめくる",
  320. loadConfirm:"数ページめくりたいですか?(0は途切れない)",
  321. noNext:"次のページが見つかりません、新しいルールを作成してください",
  322. passSec: "#t#秒前に更新",
  323. passMin: "#t#分前に更新",
  324. passHour: "#t#時間前に更新",
  325. passDay: "#t#日前に更新",
  326. cantDel: "組み込みルールを削除できません",
  327. confirmDel: "このルールを削除してもよろしいですか?",
  328. updateSucc: "更新に成功しました",
  329. beginUpdate: "更新中、お待ちください",
  330. customUrls: "インポートルールのURL、1行に1つ",
  331. customRules: "【東方永頁機】の形式でカスタムルールを入力してください",
  332. save: "設定を保存",
  333. loadingText: "少女祈祷中...",
  334. opacity:"不透明値",
  335. opacityPlaceholder:"0: 隠す",
  336. hideBar:"ページ区切り文字を非表示にします",
  337. hideBarButNoStop:"非表示にするが停止しない",
  338. dbClick2Stop:"空白部分をダブルクリックしてページめくりを一時停止します",
  339. sortTitle:"並べ替えは、次のルールの更新後に有効になります",
  340. autoRun:"自動的に有効",
  341. autoLoadNum:"指定したページ数を自動的に読み込みます",
  342. inputPageNum:"ジャンプするページ番号を入力",
  343. enableHistory:"ページめくり後の履歴を書く",
  344. enableHistoryAfterInsert: "スプライシングの直後に履歴レコードを書き込みます。それ以外の場合は、閲覧後に書き込みます",
  345. initRun:"Webページを開いた直後にページをめくる",
  346. preload:"事前に次のページを読む",
  347. click2ImportRule:"以下をクリックして、ルールベースを追加します:",
  348. forceAllBody:"フルページ埋め込み?",
  349. openInNewTab:"スプライスされたページのコンテンツを新しいページで開きます",
  350. importSucc:"インポート完了",
  351. import:"インポート",
  352. editCurrent:"現在のルールの編集",
  353. editBlacklist:"ブラックリストのURLを編集し、1行ずつ、サポート? *ワイルドカード",
  354. upBtnImg:"トップアイコンに戻る",
  355. downBtnImg:"フッターアイコンに移動",
  356. loadingTextTitle:"テキストをロード",
  357. dbClick2StopCtrl:"Ctrlキー",
  358. dbClick2StopAlt:"Altキー",
  359. dbClick2StopShift:"Shiftキー",
  360. dbClick2StopMeta:"Metaキー",
  361. dbClick2StopKey:"Shortcutキー",
  362. pageElementCss:"ページ本文フレームの STYLE",
  363. customCss:"カスタム CSS",
  364. firstAlert:"ルールベースをインポートしていないため、インポートする適切なルールベースを選択してください",
  365. picker:"Pagetualページ要素ピッカー",
  366. closePicker:"Pagetualピッカーを閉じる",
  367. pickerPlaceholder:"わからない場合は空のままにしてください",
  368. pickerCheck:"セレクターをチェックしてコピー",
  369. switchSelector:"クリックして要素を切り替えます",
  370. gotoEdit:"現在のセレクターでルールを編集する",
  371. manualMode:"スプライシングを無効にします。手動で右の矢印キーを使用してページをめくります",
  372. clickMode: "スティッチングを無効にします。ページの最後までスクロールすると、次のページが自動的にクリックされます",
  373. pageBarMenu:"ページバーの中央をクリックしてメニューをポップアップ表示",
  374. nextSwitch:"次のページに切り替え",
  375. arrowToScroll:"左矢印キーで前へ、右矢印キーで次へ",
  376. hideLoadingIcon:"読み込み中のアニメーションを隠す",
  377. duplicate: "Pagetual の重複インストールが検出されました。他のスクリプト マネージャで永続的なページ マシンを削除してください!",
  378. forceStateIframe: "iframe にページ全体を埋め込む",
  379. forceStateDynamic: "iframe 経由で動的コンテンツを読み込む",
  380. forceStateDisable: "このステーションでのページめくりを無効にする"
  381. };
  382. break;
  383. case "ru":
  384. case "ru-RU":
  385. config = {
  386. enableDebug:"Включить отладку",
  387. disable:"Отключено",
  388. disableSite:"Переключить состояние отключения",
  389. disableSiteTips:"Отключено на этом сайте",
  390. enableSiteTips:"Включено на этом сайте",
  391. enable:"Включено",
  392. toTop:"В начало",
  393. toBottom:"В конец",
  394. current:"Текущая страница",
  395. forceIframe:"Принудительно присоединить следующую страницу",
  396. cancelForceIframe:"Отменить принудительное присоединение",
  397. configure:"Настроить",
  398. firstUpdate:"Нажмите здесь, чтобы инициализировать правила",
  399. update:"Обновить правила онлайн",
  400. click2update:"Нажмите, чтобы обновить правила по URL сейчас",
  401. loadNow:"Загрузить следующую страницу сейчас",
  402. loadConfirm:"Сколько страниц вы хотите загрузить? (0 означает бесконечность)",
  403. noNext:"Ссылка на следующую страницу не найдена, пожалуйста, создайте новое правило",
  404. passSec:"Обновлено #t# секунд назад",
  405. passMin:"Обновлено #t# минут назад",
  406. passHour:"Обновлено #t# часов назад",
  407. passDay:"Обновлено #t# дней назад",
  408. cantDel:"Невозможно удалить встроенные правила",
  409. confirmDel:"Вы уверены, что хотите удалить это правило?",
  410. updateSucc:"Обновление прошло успешно",
  411. beginUpdate:"Обновление начато, подождите минуту, пожалуйста",
  412. customUrls:"Импортируйте URL-адрес правила Пэйджтуал или AutoPagerize по одному URL на строку",
  413. customRules:"Введите пользовательские правила с форматом [Pagetual]",
  414. save:"Сохранить",
  415. loadingText:"Shojo загружается...",
  416. opacity:"Непрозрачность",
  417. opacityPlaceholder:"0: скрыть",
  418. hideBar:"Скрыть промежуток переключения страниц",
  419. hideBarButNoStop:"Скрыть, но не останавливать",
  420. dbClick2Stop:"Двойной щелчок по пустому пространству для паузы",
  421. sortTitle:"Сортировка вступает в силу после следующего обновления правила",
  422. autoRun:"Автозапуск (режим черного списка)",
  423. autoLoadNum:"Количество для предварительной загрузки страниц",
  424. inputPageNum:"Введите номер страницы для перехода",
  425. enableHistory:"Записать историю после переключения страниц",
  426. enableHistoryAfterInsert: "Записать запись истории сразу после сплайсинга, в противном случае запишите после просмотра",
  427. initRun:"Переключать страницы сразу после открытия",
  428. preload:"Предварительная загрузка следующей страницы для ускорения",
  429. click2ImportRule:"Нажмите, чтобы импортировать ссылку базовых правил, затем дождитесь завершения обновления:",
  430. forceAllBody:"Присоединить полное тело страницы?",
  431. openInNewTab:"Открыть дополнительные URL-адреса в новой вкладке",
  432. importSucc:"Импорт завершен",
  433. import:"Импорт",
  434. editCurrent:"Редактировать правило для текущего",
  435. editBlacklist:"Редактировать URL-адреса черного списка, по одной строке, поддержка ? * для подстановочного знака",
  436. upBtnImg:"Иконка перехода к началу страницы",
  437. downBtnImg:"Иконка перехода к концу страницы",
  438. loadingTextTitle:"Текст загрузки",
  439. dbClick2StopCtrl:"Клавиша Ctrl",
  440. dbClick2StopAlt:"Клавиша Alt",
  441. dbClick2StopShift:"Клавиша Shift",
  442. dbClick2StopMeta:"Клавиша Meta",
  443. dbClick2StopKey:"Клавиша быстрого доступа",
  444. pageElementCss:"Пользовательский стиль для основных элементов страницы",
  445. customCss:"Полный пользовательский CSS",
  446. firstAlert:"Вы не импортировали базовое правило, пожалуйста, выберите соответствующее правило для импорта",
  447. picker:"Выбор элемента страницы Пэйджтуал",
  448. closePicker:"Закрыть выбор Пэйджтуал",
  449. pickerPlaceholder:"Оставьте пустым, если вы не знаете",
  450. pickerCheck:"Проверить селектор и скопируй",
  451. switchSelector:"нажмите для переключения элемента",
  452. gotoEdit:"Перейти к редактированию правила с текущим селектором",
  453. manualMode:"Отключить автоматическую перелистывание страниц, перелистывать страницы вручную с помощью стрелок справа (или вызвать событие 'pagetual.next')",
  454. clickMode: "Отключить \"сшивание\" страниц, т.е. автоматически переходить на следующую страницу при прокрутке к ее концу",
  455. pageBarMenu:"Щелкните середину панели страниц, чтобы открыть меню.",
  456. nextSwitch:"Переключить ссылку на следующую страницу",
  457. arrowToScroll:"Нажмите клавишу со стрелкой влево для предыдущего и клавишу со стрелкой вправо для следующего",
  458. hideLoadingIcon:"Скрыть анимацию загрузки",
  459. duplicate: "Обнаружена двойная установка Pagetual, пожалуйста, удалите постоянную страничную машину в других менеджерах скриптов!",
  460. forceStateIframe: "Вставить полную страницу как iframe",
  461. forceStateDynamic:"Загружать динамический контент через iframe",
  462. forceStateDisable: "Отключить перелистывание страниц на этой станции"
  463. };
  464. break;
  465. default:
  466. config = {
  467. enableDebug:"Enable debug output",
  468. disable:"Disable",
  469. disableSite:"Toggle disabled state",
  470. disableSiteTips:"Disabled on this site",
  471. enableSiteTips:"Enabled on this site",
  472. enable:"Enable",
  473. toTop:"To Top",
  474. toBottom:"To Bottom",
  475. current:"Current Page",
  476. forceIframe:"Force to join next page",
  477. cancelForceIframe:"Cancel Force join",
  478. configure:"Configure",
  479. firstUpdate:"Click here to initialize the rules",
  480. update:"Update online rules",
  481. click2update:"Click to update rules from url now",
  482. loadNow:"Load next page manually",
  483. loadConfirm:"How much pages do you want to load? (0 means infinite)",
  484. noNext:"No next link found, please create a new rule",
  485. passSec:"Updated #t# seconds ago",
  486. passMin:"Updated #t# minutes ago",
  487. passHour:"Updated #t# hours ago",
  488. passDay:"Updated #t# days ago",
  489. cantDel:"Can't delete buildin rules",
  490. confirmDel:"Are you sure you want to delete this rule?",
  491. updateSucc:"Update succeeded",
  492. beginUpdate:"Begin update, wait a minute please",
  493. customUrls:"Import Pagetual or AutoPagerize rule url, One url per line",
  494. customRules:"Input custom rules with [Pagetual] format",
  495. save:"Save",
  496. loadingText:"Shojo Now Loading...",
  497. opacity:"Opacity",
  498. opacityPlaceholder:"0: hide spacer",
  499. hideBar:"Hide the paging spacer",
  500. hideBarButNoStop:"Hide but not stop",
  501. dbClick2Stop:"Double-click on the blank space to pause",
  502. sortTitle:"Sorting takes effect after the next rule update",
  503. autoRun:"Auto run (black list mode)",
  504. autoLoadNum:"Amount for preload pages",
  505. inputPageNum:"Enter page number to jump",
  506. enableHistory:"Write history after page turning",
  507. enableHistoryAfterInsert: "Write history immediately after splicing, otherwise write after browsing",
  508. initRun:"Turn pages immediately after opening",
  509. preload:"Preload next page for speeding up",
  510. click2ImportRule:"Click to import base rules link, then wait until the update is complete:",
  511. forceAllBody:"Join full body of page?",
  512. openInNewTab:"Open urls of additions in new tab",
  513. importSucc:"Import completed",
  514. import:"Import",
  515. editCurrent:"Edit rule for current",
  516. editBlacklist:"Edit the blacklist urls, line by line, Support ? * for wildcard",
  517. upBtnImg:"Icon of back to top",
  518. downBtnImg:"Icon of go to footer",
  519. loadingTextTitle:"Loading text",
  520. dbClick2StopCtrl:"Ctrl key",
  521. dbClick2StopAlt:"Alt key",
  522. dbClick2StopShift:"Shift key",
  523. dbClick2StopMeta:"Meta key",
  524. dbClick2StopKey:"Shortcut key",
  525. pageElementCss:"Custom style for main page elements",
  526. customCss:"Custom complete css",
  527. firstAlert:"You have not imported the base rule, please select the appropriate rule to import",
  528. picker:"Pagetual page element picker",
  529. closePicker:"Close Pagetual picker",
  530. pickerPlaceholder:"Leave empty if you have no idea",
  531. pickerCheck:"Check selector and copy",
  532. switchSelector:"Click to switch element",
  533. gotoEdit:"Go to edit rule with current selector",
  534. manualMode:"Disable splicing, manually turn pages with the right arrow keys (or dispatch event 'pagetual.next')",
  535. clickMode: "Disable splicing, automatically click the next page when scrolling to the end of the page",
  536. pageBarMenu:"Click the middle of the page bar to open the menu",
  537. nextSwitch:"Switch next link",
  538. arrowToScroll:"Press left arrow key to scroll prev and right arrow key to scroll next",
  539. hideLoadingIcon:"Hide loading animation",
  540. duplicate:"Duplicate Pagetual have been installed, check your script manager!",
  541. forceStateIframe: "Embed full page as iframe",
  542. forceStateDynamic: "Load dynamic content via iframe",
  543. forceStateDisable: "Disable page turning on this site"
  544. };
  545. break;
  546. }
  547. var enableDebug=true;
  548. function i18n(name, param) {
  549. return config[name]?config[name].replace("#t#",param):name;
  550. };
  551.  
  552. function debug(str, title) {
  553. if(enableDebug){
  554. console.log(
  555. `%cPagetual v.${_GM_info.script.version}】 ${title ? title : 'debug'}:`,
  556. 'color: yellow;font-size: large;font-weight: bold;background-color: darkblue;',
  557. str
  558. );
  559. }
  560. };
  561.  
  562. var _GM_xmlhttpRequest,_GM_registerMenuCommand,_GM_notification,_GM_addStyle,_GM_openInTab,_GM_info,_GM_setClipboard;
  563. if(typeof GM_xmlhttpRequest!='undefined'){
  564. _GM_xmlhttpRequest=GM_xmlhttpRequest;
  565. }else if(typeof GM!='undefined' && typeof GM.xmlHttpRequest!='undefined'){
  566. _GM_xmlhttpRequest=GM.xmlHttpRequest;
  567. }else{
  568. _GM_xmlhttpRequest=(f)=>{fetch(f.url).then(response=>response.text()).then(data=>{let res={response:data};f.onload(res)}).catch(e => f.onerror(e))};
  569. }
  570. if(typeof GM_registerMenuCommand!='undefined'){
  571. _GM_registerMenuCommand=GM_registerMenuCommand;
  572. }else if(typeof GM!='undefined' && typeof GM.registerMenuCommand!='undefined'){
  573. _GM_registerMenuCommand=GM.registerMenuCommand;
  574. }else{
  575. _GM_registerMenuCommand=(s,f)=>{};
  576. }
  577. if(typeof GM_info!='undefined'){
  578. _GM_info=GM_info;
  579. }else if(typeof GM!='undefined' && typeof GM.info!='undefined'){
  580. _GM_info=GM.info;
  581. }else{
  582. _GM_info={script:1};
  583. }
  584. if(typeof GM_notification!='undefined'){
  585. _GM_notification=GM_notification;
  586. }else if(typeof GM!='undefined' && typeof GM.notification!='undefined'){
  587. _GM_notification=GM.notification;
  588. }else{
  589. _GM_notification=(s)=>{showTips(s)};
  590. }
  591. if(typeof GM_openInTab!='undefined'){
  592. _GM_openInTab=GM_openInTab;
  593. }else if(typeof GM!='undefined' && typeof GM.openInTab!='undefined'){
  594. _GM_openInTab=GM.openInTab;
  595. }else{
  596. _GM_openInTab=(s,t)=>{window.open(s)};
  597. }
  598. if(typeof GM_addStyle!='undefined'){
  599. _GM_addStyle=GM_addStyle;
  600. }else if(typeof GM!='undefined' && typeof GM.addStyle!='undefined'){
  601. _GM_addStyle=GM.addStyle;
  602. }else{
  603. _GM_addStyle=cssStr=>{
  604. let styleEle=document.createElement("style");
  605. styleEle.innerHTML=cssStr;
  606. document.head.appendChild(styleEle);
  607. return styleEle;
  608. };
  609. }
  610. if (typeof GM_setClipboard != 'undefined') {
  611. _GM_setClipboard = GM_setClipboard;
  612. } else if (typeof GM != 'undefined' && typeof GM.setClipboard != 'undefined') {
  613. _GM_setClipboard = GM.setClipboard;
  614. } else {
  615. _GM_setClipboard = (s, i) => {};
  616. }
  617. var _unsafeWindow=(typeof unsafeWindow=='undefined')?window:unsafeWindow;//兼容 ios userscripts 的寫法
  618. var storage={
  619. supportGM: typeof GM_getValue=='function' && typeof GM_getValue('a','b')!='undefined',
  620. supportGMPromise: typeof GM!='undefined' && typeof GM.getValue=='function' && typeof GM.getValue('a','b')!='undefined',
  621. mxAppStorage:(function(){
  622. try{
  623. return window.external.mxGetRuntime().storage;
  624. }catch(e){
  625. }
  626. })(),
  627. operaUJSStorage:(function(){
  628. try{
  629. return window.opera.scriptStorage;
  630. }catch(e){
  631. }
  632. })(),
  633. setItem:function(key,value){
  634. if(this.operaUJSStorage){
  635. this.operaUJSStorage.setItem(key,value);
  636. }else if(this.mxAppStorage){
  637. this.mxAppStorage.setConfig(key,value);
  638. }else if(this.supportGM){
  639. GM_setValue(key,value);
  640. if(value==="" && typeof GM_deleteValue!='undefined'){
  641. GM_deleteValue(key);
  642. }
  643. }else if(this.supportGMPromise){
  644. GM.setValue(key,value);
  645. if(value==="" && typeof GM!='undefined' && typeof GM.deleteValue!='undefined'){
  646. GM.deleteValue(key);
  647. }
  648. }else if(window.localStorage){
  649. window.localStorage.setItem(key,value);
  650. }
  651. },
  652. getItem:function(key,cb){
  653. var value;
  654. if(this.operaUJSStorage){
  655. value=this.operaUJSStorage.getItem(key);
  656. }else if(this.mxAppStorage){
  657. value=this.mxAppStorage.getConfig(key);
  658. }else if(this.supportGM){
  659. value=GM_getValue(key);
  660. }else if(this.supportGMPromise){
  661. value=GM.getValue(key).then(v=>{cb(v)});
  662. return;
  663. }else if(window.localStorage){
  664. value=window.localStorage.getItem(key);
  665. };
  666. cb(value);
  667. }
  668. };
  669. var rulesData={},ruleUrls,updateDate;
  670. const configPage=["https://github.com/hoothin/UserScripts/tree/master/Pagetual",
  671. "https://hoothin.github.io/UserScripts/Pagetual/"];
  672. const guidePage=/^https?:\/\/.*\/PagetualGuide\/.*rule\.html/;
  673. const ruleImportUrlReg=/greasyfork\.org\/.*scripts\/438684[^\/]*(\/discussions|\/?$)|github\.com\/hoothin\/UserScripts\/(tree\/master\/Pagetual|issues\/)/i;
  674. const allOfBody="body>*";
  675. _GM_registerMenuCommand(i18n("configure"), ()=>{
  676. _GM_openInTab(configPage[0],{active:true});
  677. });
  678. _GM_registerMenuCommand(i18n("editCurrent"), ()=>{
  679. Picker.getInstance().start();
  680. });
  681.  
  682. function getElementByXpath(xpath, contextNode, doc){
  683. doc = doc || document;
  684. contextNode = contextNode || doc;
  685. try {
  686. var result = doc.evaluate(xpath, contextNode, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
  687. return result.singleNodeValue && result.singleNodeValue.nodeType === 1 && result.singleNodeValue;
  688. } catch (err) {
  689. debug(`Invalid xpath: ${xpath}`);
  690. }
  691. return null;
  692. }
  693.  
  694. function getAllElementsByXpath(xpath, contextNode, doc){
  695. doc = doc || document;
  696. contextNode = contextNode || doc;
  697. var result = [];
  698. try {
  699. var query = doc.evaluate(xpath, contextNode, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  700. for (var i = 0; i < query.snapshotLength; i++) {
  701. var node = query.snapshotItem(i);
  702. if (node.nodeType === 1) result.push(node);
  703. }
  704. } catch (err) {
  705. debug(`Invalid xpath: ${xpath}`);
  706. }
  707. return result;
  708. }
  709.  
  710. function isXPath(xpath) {
  711. if (!xpath) return false;
  712. return /^\(*(descendant::|\.\/|\/\/|id\()/.test(xpath);
  713. }
  714.  
  715. function getAllElements(sel, doc) {
  716. try {
  717. if (!isXPath(sel)) {
  718. return doc.querySelectorAll(sel);
  719. }
  720. } catch(e) {
  721. debug(e, 'Error selector');
  722. }
  723. return getAllElementsByXpath(sel, doc, doc);
  724. }
  725.  
  726. function getElement(sel, doc) {
  727. try {
  728. if (!isXPath(sel)) {
  729. return doc.querySelector(sel);
  730. }
  731. } catch(e) {
  732. debug(e, 'Error selector');
  733. }
  734. return getElementByXpath(sel, doc, doc);
  735. }
  736.  
  737. function geneSelector(ele, addID) {
  738. let selector = ele.tagName.toLowerCase();
  739. //Google id class都是隨機。百度更過分,style script順序都是隨機的
  740. if (ele.tagName != "HTML" && ele.tagName != "BODY") {
  741. let hasId = false;
  742. if (addID && ele.id && /^[a-z_][\w\-_]*$/i.test(ele.id)) {
  743. hasId = true;
  744. selector += '#' + ele.id;
  745. }
  746. let className = "";
  747. if (ele.className) {
  748. let classList = ele.classList, i = 0;
  749. for (let i = 0; i < classList.length; i++) {
  750. let c = classList[i];
  751. if (/^[\w\-_]+$/.test(c) && !/\d{3,}/.test(c)) {
  752. className += '.' + c;
  753. }
  754. }
  755. selector += className;
  756. }
  757. let parent = ele.parentElement;
  758. if (parent) {
  759. selector = geneSelector(parent, addID) + ' > ' + selector;
  760. if (!className && !hasId && parent.children.length > 1) {
  761. let i, j = 0;
  762. for (i = 0; i < parent.children.length; i++) {
  763. if (parent.children[i].tagName == ele.tagName) {
  764. j++;
  765. if (parent.children[i] == ele) {
  766. break;
  767. }
  768. }
  769. }
  770. selector += (parent.tagName == "HTML" ? "" : `:nth-of-type(${j})`);
  771. }
  772. }
  773. }
  774. return selector;
  775. }
  776.  
  777. function createXPathFromElement(elm) {
  778. let allNodes = document.getElementsByTagName('*'), segs;
  779. for (segs = []; elm && elm.nodeType == 1; elm = elm.parentNode) {
  780. if (elm.hasAttribute('id')) {
  781. var uniqueIdCount = 0;
  782. for (var n=0;n < allNodes.length;n++) {
  783. if (allNodes[n].hasAttribute('id') && allNodes[n].id == elm.id) uniqueIdCount++;
  784. if (uniqueIdCount > 1) break;
  785. }
  786. if ( uniqueIdCount == 1) {
  787. segs.unshift('id("' + elm.getAttribute('id') + '")');
  788. return segs.join('/');
  789. } else {
  790. segs.unshift(elm.localName.toLowerCase() + '[@id="' + elm.getAttribute('id') + '"]');
  791. }
  792. } else if (elm.hasAttribute('class')) {
  793. segs.unshift(elm.localName.toLowerCase() + '[@class="' + elm.getAttribute('class') + '"]');
  794. } else {
  795. let i, sib;
  796. for (i = 1, sib = elm.previousSibling; sib; sib = sib.previousSibling) {
  797. if (sib.localName == elm.localName) i++;
  798. }
  799. segs.unshift(elm.localName.toLowerCase() + '[' + i + ']');
  800. }
  801. }
  802. return segs.length ? '/' + segs.join('/') : null;
  803. }
  804.  
  805. var escapeHTMLPolicy;
  806. if (_unsafeWindow.trustedTypes && _unsafeWindow.trustedTypes.createPolicy) {
  807. escapeHTMLPolicy = _unsafeWindow.trustedTypes.createPolicy('default', {
  808. createHTML: (string, sink) => string
  809. });
  810. }
  811.  
  812. function createHTML(html){
  813. return escapeHTMLPolicy?escapeHTMLPolicy.createHTML(html):html;
  814. }
  815.  
  816. const AsyncFunction = Object.getPrototypeOf(async function(){}).constructor;
  817.  
  818. class RuleParser {
  819. constructor() {
  820. this.hpRules = [];
  821. this.smartRules = [];
  822. this.customRules = [];
  823. this.rules = [];
  824. this.pageDoc = document;
  825. this.nextLinkHref = null;
  826. this.nextTitle = "";
  827. this.oldUrl = "";
  828. this.curUrl = location.href;
  829. this.curSiteRule = {};
  830. this.initGetPage = true;
  831. }
  832.  
  833. initSavedRules(callback) {
  834. var self = this;
  835. storage.getItem("smartRules", smartRules => {
  836. if (smartRules) self.smartRules = smartRules;
  837. storage.getItem("hpRules", hpRules => {
  838. if (hpRules) self.hpRules = hpRules;
  839. storage.getItem("customRules", customRules => {
  840. if (customRules) self.customRules = customRules;
  841. storage.getItem("rules", rules => {
  842. if (rules) self.rules = rules;
  843. callback();
  844. });
  845. });
  846. });
  847. });
  848. }
  849.  
  850. saveCurSiteRule(){
  851. /*if(!this.curSiteRule || !this.curSiteRule.url || this.curSiteRule.singleUrl || this.curSiteRule.url.length<13)return;
  852. this.hpRules=this.hpRules.filter(item=>{return item&&item.url!=this.curSiteRule.url});
  853. this.hpRules.unshift(this.curSiteRule);
  854. if(this.hpRules.length>30){
  855. this.hpRules.pop();
  856. }
  857. storage.setItem("hpRules", this.hpRules);*/
  858. }
  859.  
  860. requestJSON(url, callback){
  861. _GM_xmlhttpRequest({
  862. url: url,
  863. method: 'GET',
  864. timeout: 20000,
  865. onload: function(res) {
  866. let json=null;
  867. try{
  868. json=JSON.parse(res.response||res.responseText);
  869. }catch(e){
  870. debug(e, 'Error json');
  871. }
  872. callback(json);
  873. },
  874. onerror: function(e) {
  875. callback(null, e);
  876. },
  877. ontimeout: function(e) {
  878. callback(null, e);
  879. }
  880. });
  881. }
  882.  
  883. formatRule(item, from){
  884. if(item.data && item.data.url){
  885. let result = {
  886. name:item.name,
  887. from:from,
  888. action:item.data.forceIframe=="true"?1:0,
  889. url:item.data.url,
  890. pageElement:item.data.pageElement,
  891. nextLink:item.data.nextLink,
  892. insert:item.data.insertBefore||undefined,
  893. updatedAt:item.updated_at
  894. };
  895. let _css = (item.data.Stylus || '') + (item.data.CSS || '');
  896. if (_css) result.css = _css;
  897. if (item.data.bookmarklet) result.pageAction = item.data.bookmarklet;
  898. return result;
  899. }else{
  900. item.from=from;
  901. return item;
  902. }
  903. return null;
  904. }
  905.  
  906. addRuleByUrl(url, from, callback) {
  907. if(url.indexOf("?")==-1){
  908. url=url+"?"+Date.now();
  909. }else{
  910. url=url+"&"+Date.now();
  911. }
  912. this.requestJSON(url, (json,err)=>{
  913. if(!json){
  914. debug(err, "Update "+url+" rules fail!");
  915. }
  916. this.addRules(json, from);
  917. callback(json, err);
  918. });
  919. }
  920.  
  921. addRules(rules, from) {
  922. if(rules && rules.length>0){
  923. this.rules=this.rules.filter(item=>{return item.from!=from});
  924. rules.forEach(item=>{
  925. let rule=this.formatRule(item, from);
  926. if(rule){
  927. this.rules.unshift(rule);
  928. }
  929. });
  930. }
  931. }
  932.  
  933. ruleMatch(r) {
  934. let findIndex = 0;
  935. if (r.nextLink && r.nextLink != "0" && r.nextLink != 0) {
  936. let nextLinkSel = r.nextLink, nextLink;
  937. if (Array && Array.isArray && Array.isArray(nextLinkSel)) {
  938. nextLink = !nextLinkSel.every((sel, i) => {
  939. let ele = getElement(sel, document);
  940. if (ele) findIndex = i;
  941. return !ele;
  942. });
  943. } else nextLink = getElement(nextLinkSel, document);
  944. if (!nextLink) return false;
  945. }
  946. if (r.pageElement) {
  947. let pageElementSel = r.pageElement, pageElement;
  948. if (Array && Array.isArray && Array.isArray(pageElementSel)) {
  949. pageElementSel = pageElementSel[findIndex];
  950. }
  951. pageElement = getElement(pageElementSel, document);
  952. if (!pageElement) return false;
  953. }
  954. if (r.insert) {
  955. let insertSel = r.insert, insert;
  956. if (Array && Array.isArray && Array.isArray(insertSel)) {
  957. insertSel = insertSel[findIndex];
  958. }
  959. insert = getElement(insertSel, document);
  960. if (!insert) return false;
  961. }
  962. //if (findIndex !== 0) nextIndex = findIndex;
  963. return true;
  964. }
  965.  
  966. scrollToShow(sel, doc) {
  967. let exclude = getElement(sel, doc);
  968. if (exclude) {
  969. var actualTop = exclude.offsetTop;
  970. var current = exclude.offsetParent;
  971. while (current !== null) {
  972. actualTop += current.offsetTop;
  973. current = current.offsetParent;
  974. }
  975. doc.body.scrollTop = 0;
  976. doc.documentElement.scrollTop = 0;
  977. let maxHeight = Math.max(doc.body.scrollHeight, doc.documentElement.scrollHeight);
  978. doc.body.scrollTop = actualTop - 10;
  979. doc.documentElement.scrollTop = actualTop - 10;
  980. setTimeout(() => {
  981. while (actualTop < maxHeight) {
  982. actualTop += 200;
  983. doc.body.scrollTop = actualTop;
  984. doc.documentElement.scrollTop = actualTop;
  985. }
  986. }, 0);
  987. return false;
  988. }
  989. return true;
  990. }
  991.  
  992. waitElement(doc, selArr) {
  993. if (!selArr) selArr = this.curSiteRule.waitElement;
  994. if (selArr[0].trim()) {
  995. let include = getElement(selArr[0], doc);
  996. if (!include) {
  997. if (selArr.length == 2 && selArr[1].trim()) {
  998. this.scrollToShow(selArr[1], doc);
  999. }
  1000. return false;
  1001. }
  1002. }
  1003. if (doc === document) return true;
  1004. if (selArr.length == 2 && selArr[1].trim()) {
  1005. if (!this.scrollToShow(selArr[1], doc)) {
  1006. if (!document.documentElement.contains(loadingDiv) && this.insert.parentNode) {
  1007. this.insertElement(loadingDiv);
  1008. }
  1009. return false;
  1010. }
  1011. }
  1012. return true;
  1013. }
  1014.  
  1015. getRule(callback) {
  1016. if(noRuleTest){
  1017. this.curSiteRule={};
  1018. this.curSiteRule.url=location.origin+location.pathname;
  1019. this.curSiteRule.singleUrl=true;
  1020. callback();
  1021. return;
  1022. }
  1023. if(this.curSiteRule && this.curSiteRule.url){
  1024. return this.curSiteRule;
  1025. }
  1026. var self=this;
  1027.  
  1028. function setRule(r) {
  1029. self.curSiteRule=r;
  1030. if (!r.singleUrl) {
  1031. debug(r, 'Match rule');
  1032. }
  1033. callback();
  1034. }
  1035.  
  1036. function checkRule(r) {
  1037. if (r.from == 1 && r.url.length <= 13) return false;
  1038. let urlReg=new RegExp(r.url, "i");
  1039. if(urlReg.test(location.href)){
  1040. if(r.include){
  1041. let include=getElement(r.include, document);
  1042. if(!include)return false;
  1043. }
  1044. if(r.exclude){
  1045. let exclude=getElement(r.exclude, document);
  1046. if(exclude)return false;
  1047. }
  1048. if(r.waitElement){
  1049. let waitTime=500;
  1050. let checkReady=()=>{
  1051. setTimeout(()=>{
  1052. if(!self.waitElement(document, r.waitElement)){
  1053. checkReady();
  1054. }else{
  1055. setRule(r);
  1056. }
  1057. },parseInt(waitTime));
  1058. };
  1059. checkReady();
  1060. return true;
  1061. }else if(r.wait){
  1062. let waitTime=500, checkEval, maxCheckTimes=20;
  1063. if(isNaN(r.wait)){
  1064. try{
  1065. checkEval=(typeof _unsafeWindow.pagetualWait=='undefined') ? Function("doc",'"use strict";' + r.wait) : _unsafeWindow.pagetualWait;
  1066. }catch(e){
  1067. debug(e, 'Error when checkeval');
  1068. }
  1069. }else{
  1070. waitTime=r.wait;
  1071. }
  1072. let checkReady=()=>{
  1073. if(maxCheckTimes--<=0){
  1074. debug("Wait for rule ready but failed");
  1075. setRule(r);
  1076. return;
  1077. }
  1078. setTimeout(()=>{
  1079. if(!self.ruleMatch(r) || (checkEval && !checkEval(document))){
  1080. checkReady();
  1081. }else{
  1082. setRule(r);
  1083. }
  1084. },parseInt(waitTime));
  1085. };
  1086. checkReady();
  1087. return true;
  1088. }
  1089. if(r.pinUrl){
  1090. setRule(r);
  1091. return true;
  1092. }
  1093. if(!self.ruleMatch(r)){
  1094. return false;
  1095. }
  1096. setRule(r);
  1097. return true;
  1098. }
  1099. return false;
  1100. }
  1101.  
  1102. for (let i in this.hpRules) {
  1103. let rule = this.hpRules[i];
  1104. if (!rule || !rule.url) continue;
  1105. if (rule.singleUrl) {
  1106. continue;
  1107. }
  1108. if (checkRule(rule)) return;
  1109. }
  1110. for (let i in this.customRules) {
  1111. let rule = this.customRules[i];
  1112. if (!rule || !rule.url) continue;
  1113. if (checkRule(rule)) return;
  1114. }
  1115. for (let i in this.smartRules) {
  1116. let rule = this.smartRules[i];
  1117. if (!rule || !rule.url) continue;
  1118. if (rule.singleUrl) {
  1119. if (location.origin + location.pathname == rule.url) {
  1120. setRule(rule);
  1121. return;
  1122. }
  1123. continue;
  1124. }
  1125. }
  1126. let r = 0;
  1127. function searchByTime(){
  1128. setTimeout(()=>{
  1129. let end=r+50;
  1130. end=end>self.rules.length?self.rules.length:end;
  1131. for(;r<end;r++){
  1132. let rule=self.rules[r];
  1133. if(checkRule(rule))return;
  1134. }
  1135. if(end>=self.rules.length){
  1136. self.curSiteRule={};
  1137. self.curSiteRule.url=location.origin+location.pathname;
  1138. self.curSiteRule.singleUrl=true;
  1139. callback();
  1140. return;
  1141. }else{
  1142. searchByTime();
  1143. }
  1144. },1);
  1145. }
  1146. searchByTime();
  1147. }
  1148.  
  1149. replaceElement(doc) {
  1150. if (!doc || doc === document) return;
  1151. let replaceElementSel = this.curSiteRule.replaceElement;
  1152. if (replaceElementSel) {
  1153. if (!Array.isArray(replaceElementSel)) {
  1154. replaceElementSel = [replaceElementSel];
  1155. }
  1156. replaceElementSel.forEach(sel => {
  1157. let pageEles = getAllElements(sel, document);
  1158. let replaceEles = getAllElements(sel, doc);
  1159. for (let i = 0; i < pageEles.length; i++) {
  1160. let replaceEle = replaceEles[i];
  1161. let pageEle = pageEles[i];
  1162. if (replaceEle) {
  1163. pageEle.parentNode.replaceChild(replaceEle.cloneNode(true), pageEle);
  1164. } else break;
  1165. }
  1166. });
  1167. }
  1168. }
  1169.  
  1170. refreshByClick() {
  1171. let refreshByClickSel = this.curSiteRule.refreshByClick;
  1172. if (refreshByClickSel) {
  1173. document.addEventListener("click", e => {
  1174. let checkEles = getAllElements(refreshByClickSel, document);
  1175. for (let i = 0; i < checkEles.length; i++) {
  1176. if (checkEles[i] === e.target) {
  1177. urlChanged = true;
  1178. isPause = true;
  1179. if (!ruleParser.nextLinkHref) isLoading = false;
  1180. break;
  1181. }
  1182. }
  1183. });
  1184. }
  1185. }
  1186.  
  1187. getPageElement(doc, curWin, dontFind) {
  1188. if(doc==document && this.docPageElement){
  1189. let parent=this.docPageElement;
  1190. while(parent && parent.nodeName!="BODY"){
  1191. parent=parent.parentNode;
  1192. }
  1193. if(parent && parent.nodeName=="BODY"){
  1194. return this.docPageElement;
  1195. }
  1196. }
  1197. let pageElement=null;
  1198. let self=this;
  1199. let body=doc.body;
  1200. if(this.curSiteRule.pageElement){
  1201. let pageElementSel=this.curSiteRule.pageElement;
  1202. if(Array && Array.isArray && Array.isArray(pageElementSel)){
  1203. pageElementSel=pageElementSel[nextIndex<pageElementSel.length?nextIndex:0];
  1204. }
  1205. pageElement=getAllElements(pageElementSel, doc);
  1206. }
  1207. if(pageElement && pageElement.length===1 && pageElement[0].style.display==='none'){
  1208. pageElement=[body];
  1209. }
  1210. if(this.curSiteRule.singleUrl && pageElement && pageElement.length>0 && pageElement[0].tagName=="TR"){
  1211. let mainTr=this.insert.parentNode.querySelector('tr'),mainTdNum=0,newTdNum=0;
  1212. [].forEach.call(mainTr.children, el=>{
  1213. if(el.tagName=="TD" || el.tagName=="TH"){
  1214. mainTdNum+=el.colSpan||1;
  1215. }
  1216. });
  1217. [].forEach.call(pageElement[0].children, el=>{
  1218. if(el.tagName=="TD" || el.tagName=="TH"){
  1219. newTdNum+=el.colSpan||1;
  1220. }
  1221. });
  1222. if(mainTdNum!=newTdNum){
  1223. this.curSiteRule.pageElement=allOfBody;
  1224. pageElement=[body];
  1225. this.getInsert(true);
  1226. }
  1227. }
  1228. if((this.curSiteRule.singleUrl || !this.curSiteRule.pageElement) && (!pageElement || pageElement.length==0) && curWin && !dontFind){
  1229. if(!body)return null;
  1230. let bodyHeight=parseInt(body.offsetHeight || body.scrollHeight);
  1231. let curHeight=bodyHeight;
  1232. let windowHeight=window.innerHeight || document.documentElement.clientHeight;
  1233. let needCheckNext=(doc==document && this.initNext);
  1234. function checkElement(ele){
  1235. if (ele.tagName == "PRE" || ele.tagName == "CODE") {
  1236. self.curSiteRule.pageElement = geneSelector(ele.parentNode);
  1237. debug(self.curSiteRule.pageElement, 'Page element');
  1238. return [ele.parentNode];
  1239. }
  1240. if(ele.childNodes && ele.childNodes.length==1)ele=ele.childNodes[0];
  1241. if(ele.tagName=="PICTURE"){
  1242. self.curSiteRule.pageElement=geneSelector(ele.parentNode)+">"+ele.tagName.toLowerCase();
  1243. debug(self.curSiteRule.pageElement, 'Page element');
  1244. return [ele];
  1245. }
  1246. if(curHeight/bodyHeight<=0.25){
  1247. self.curSiteRule.pageElement=allOfBody;
  1248. debug(self.curSiteRule.pageElement, 'Page element');
  1249. return [body];
  1250. }
  1251. if(ele.tagName=="FORM" && ele.parentNode!=document.body){
  1252. self.curSiteRule.pageElement=geneSelector(ele)+">*";
  1253. debug(self.curSiteRule.pageElement, 'Page element');
  1254. return ele.children;
  1255. }
  1256. if(ele.children.length==0 && !self.curSiteRule.pageElement){
  1257. if(ele.parentNode.tagName=="P")ele=ele.parentNode;
  1258. self.curSiteRule.pageElement=geneSelector(ele.parentNode)+">"+ele.tagName.toLowerCase();
  1259. debug(self.curSiteRule.pageElement, 'Page element');
  1260. return [ele];
  1261. }
  1262. let i,maxHeight=curHeight*0.55,curMaxEle=null,curMaxArea=0,maxWidth=0;
  1263. let isHori=true;
  1264. let offsetTop=ele.children[0].offsetTop;
  1265. for(i=1;i<ele.children.length;i++){
  1266. if(ele.children[i].offsetTop!=offsetTop){
  1267. isHori=false;
  1268. break;
  1269. }
  1270. }
  1271. let hasSameClass = false;
  1272. let articleNum = 0;
  1273. for (i = 0; i < ele.children.length; i++) {
  1274. let curNode = ele.children[i];
  1275. if (curNode.tagName == "CANVAS") continue;
  1276. if (curNode.tagName == "NAV") continue;
  1277. if (!curNode.offsetParent) continue;
  1278. if (curNode.tagName != "IMG" && curNode.querySelector('img') == null && /^\s*$/.test(curNode.innerText)) continue;
  1279. if (needCheckNext && !curNode.contains(self.initNext) && getElementTop(curNode) > windowHeight) {
  1280. continue;
  1281. }
  1282. if (curNode.tagName == "ARTICLE") articleNum++;
  1283. let comStyle = curWin.getComputedStyle(curNode);
  1284. let h = parseInt(curNode.offsetHeight || curNode.scrollHeight);
  1285. let w = parseInt(curNode.scrollWidth);
  1286. if (isNaN(h) || isNaN(w)) continue;
  1287. if (isHori && h <= 50) continue;
  1288. let a = h * w + h, moreChild = curNode.children[0];
  1289. while (moreChild) {
  1290. comStyle = curWin.getComputedStyle(moreChild);
  1291. let ch = parseInt(moreChild.offsetHeight || moreChild.scrollHeight);
  1292. let cw = parseInt(moreChild.scrollWidth);
  1293. if (h < ch) h = ch;
  1294. if (moreChild.innerText != "" && !isNaN(ch) && !isNaN(cw)) {
  1295. a += ch * cw;
  1296. }
  1297. moreChild = moreChild.nextElementSibling;
  1298. }
  1299. let isMax = false;
  1300. if (isHori) {
  1301. if (maxWidth < w) {
  1302. isMax = true;
  1303. } else if (maxWidth < w + 300 && curMaxArea < a) {
  1304. isMax = true;
  1305. }
  1306. } else {
  1307. isMax = curMaxArea < a;
  1308. }
  1309. if (curMaxEle == null || isMax) {
  1310. if (h > 0 || !isHori) curHeight = h;
  1311. curMaxArea = a;
  1312. maxWidth = w;
  1313. curMaxEle = curNode;
  1314. }
  1315. }
  1316. if (curMaxEle) {
  1317. for(i = 0; i < ele.children.length; i++) {
  1318. let curNode = ele.children[i];
  1319. if (curMaxEle != curNode && curNode.className && curNode.style.display !== 'none' && curMaxEle.className == curNode.className && curMaxEle.tagName == curNode.tagName){
  1320. hasSameClass = true;
  1321. break;
  1322. }
  1323. }
  1324. }
  1325. if (curMaxEle && !hasSameClass && (isHori || curHeight > maxHeight || (needCheckNext && curHeight > windowHeight && ele.contains(self.initNext)))) {
  1326. return checkElement(curMaxEle);
  1327. }
  1328. if (ele.parentNode.children.length == 1 && curWin.getComputedStyle(ele.parentNode).float == 'none')ele=ele.parentNode;
  1329. else if(ele.tagName=="P" || ele.tagName=="BR")ele=ele.parentNode;
  1330. else if(ele.tagName=="TD")ele=ele.parentNode;
  1331. else if(ele.tagName=="TBODY"){
  1332. self.curSiteRule.pageElement=geneSelector(ele)+">*";
  1333. if(ele.children.length>0 && ele.children[0].querySelector("th")){
  1334. self.curSiteRule.pageElement+=":not(:first-child)";
  1335. }
  1336. debug(self.curSiteRule.pageElement, 'Page element');
  1337. return ele.children;
  1338. }
  1339. let imgs = ele.querySelectorAll('img');
  1340. if (imgs.length == 1) {
  1341. let img = imgs[0];
  1342. if (img.offsetWidth > ele.offsetWidth / 3 * 2 && img.offsetHeight > ele.offsetHeight / 2) {
  1343. ele = img;
  1344. }
  1345. }
  1346. self.curSiteRule.pageElement=geneSelector(ele);
  1347. if (ele.children.length > 1) {
  1348. if (curWin.getComputedStyle(ele).gridArea) {
  1349. self.curSiteRule.pageElement += ">*";
  1350. ele = ele.children;
  1351. } else if (articleNum > 1) {
  1352. self.curSiteRule.pageElement += ">article";
  1353. ele = ele.children;
  1354. } else {
  1355. let hasText=false;
  1356. for(let i in ele.childNodes){
  1357. let child=ele.childNodes[i];
  1358. if(child.nodeType==3 && child.nodeValue.trim()!=''){
  1359. hasText=true;
  1360. ele=[ele];
  1361. break;
  1362. }
  1363. }
  1364. if(!hasText){
  1365. let middleChild=ele.children[parseInt(ele.children.length/2)];
  1366. if(curWin.getComputedStyle(ele).display==='flex' || (rulesData.opacity!=0 && curWin.getComputedStyle(ele.parentNode).display.indexOf('flex')==-1)){
  1367. ele=[ele];
  1368. }else if((middleChild.style && middleChild.style.position=="absolute" && middleChild.style.left && middleChild.style.top) || ele.tagName=="UL" || curHeight==0){
  1369. ele=[ele];
  1370. }else{
  1371. self.curSiteRule.pageElement+=">*";
  1372. ele=ele.children;
  1373. }
  1374. }
  1375. }
  1376. }else{
  1377. ele=[ele];
  1378. }
  1379. debug(self.curSiteRule.pageElement, 'Page element');
  1380. return ele;
  1381. }
  1382. pageElement=checkElement(body);
  1383. if (pageElement && pageElement.length > 0 && self.initNext) {
  1384. let lastBottom = getElementBottom(pageElement[pageElement.length - 1]);
  1385. if (lastBottom && getElementTop(self.initNext) - lastBottom > 1000) {
  1386. debug("Stop as too long between next & page element");
  1387. isPause = true;
  1388. pageElement = [];
  1389. } else {
  1390. if (pageElement.length == 1 && pageElement[0].tagName == "IMG") {
  1391. self.curSiteRule.pageBar = 0;
  1392. }
  1393. }
  1394. }
  1395. //if(pageElement)this.saveCurSiteRule();
  1396. }
  1397. if(doc==document && !this.docPageElement){
  1398. this.docPageElement=pageElement;
  1399. }
  1400. if(pageElement && pageElement.length>0){
  1401. let pageElementCss=self.curSiteRule.pageElementCss || self.curSiteRule.pageElementStyle || rulesData.pageElementCss;
  1402. if(pageElementCss){
  1403. [].forEach.call(pageElement, ele=>{
  1404. if(!ele.dataset.pagetualPageElement){
  1405. ele.style.cssText=(ele.style.cssText||'')+pageElementCss;
  1406. ele.dataset.pagetualPageElement=1;
  1407. }
  1408. });
  1409. }
  1410. }
  1411. if (doc !== document) this.lazyImgAction(pageElement);
  1412. return pageElement;
  1413. }
  1414.  
  1415. getPage(doc){
  1416. if(typeof _unsafeWindow.Discourse!='undefined')return {};
  1417. let video=document.querySelector("video,iframe[src*=player],iframe[src*=m3u8]");
  1418. if(video){
  1419. let scrollWidth = video.scrollWidth || video.offsetWidth;
  1420. let scrollHeight = video.scrollHeight || video.offsetHeight;
  1421. if(scrollWidth>500 && scrollHeight>500){
  1422. debug("Won't run when video found");
  1423. return {};
  1424. }
  1425. }
  1426. let canSave=false;//發現頁碼選擇器在其他頁對不上,還是別保存了
  1427. let url = this.curUrl.replace("index.php?","?");
  1428. let _url=url.replace(/\.s?html?$/i,"");
  1429. let pageNum=1,preStr="",afterStr="";
  1430. let pageMatch1=url.match(/(.*[a-z\/\-_](?:p|page)?\/?)(\d+)(\.s?html?$|\/?$)/i);
  1431. let pageMatch2=url.match(/(.*[\?&]p(?:age)?=)(\d+)($|[#&].*)/i);
  1432. if(pageMatch1){
  1433. preStr=pageMatch1[1];
  1434. pageNum=parseInt(pageMatch1[2]);
  1435. afterStr=pageMatch1[3];
  1436. if (/^\/?$/.test(afterStr) && !/(p(age)?|_|\-|\/)$/.test(preStr)) {
  1437. preStr = "";
  1438. afterStr = "";
  1439. }
  1440. }else if(pageMatch2){
  1441. preStr=pageMatch2[1];
  1442. pageNum=parseInt(pageMatch2[2]);
  1443. afterStr=pageMatch2[3];
  1444. }
  1445. let curPage=doc,i,cur,jsNext,body=doc.body||doc;
  1446. let next1,next2,next3,next4,nextJs1,nextJs2,nextJs3;
  1447. let next=body.querySelector(".page-next>a")||
  1448. body.querySelector("a.next_page")||
  1449. body.querySelector("#next_page")||
  1450. body.querySelector(".nextPage")||
  1451. body.querySelector("a[data-pagination=next]")||
  1452. body.querySelector("ul.pagination>li.active+li>a")||
  1453. body.querySelector(".pagination a[rel=next]")||
  1454. body.querySelector(".pagination-nav__item--next>a")||
  1455. body.querySelector("a.pageright")||
  1456. body.querySelector(".page-numbers.current+a")||
  1457. body.querySelector("a[title='Next page']")||
  1458. body.querySelector("[title='Next page']")||
  1459. body.querySelector("[title='下一页']")||
  1460. body.querySelector("[title='下一頁']")||
  1461. body.querySelector("input[value='next']")||
  1462. body.querySelector("input[value='Next page']")||
  1463. body.querySelector("input[value='下一页']")||
  1464. body.querySelector("input[value='下一頁']")||
  1465. body.querySelector("a#pb_next")||
  1466. body.querySelector("a#rightFix")||
  1467. body.querySelector("a#btnPreGn")||
  1468. body.querySelector("a.page-next")||
  1469. body.querySelector("a.pages-next")||
  1470. body.querySelector("a.page.right")||
  1471. body.querySelector("a#next")||
  1472. body.querySelector(".next>a")||
  1473. body.querySelector(".next>button")||
  1474. body.querySelector("a[alt=next]")||
  1475. body.querySelector("button.next")||
  1476. body.querySelector("[title=next]")||
  1477. body.querySelector("a#linkNext")||
  1478. getElementByXpath("//a[contains(@class, 'page__next')]",curPage,curPage);
  1479. if(!next){
  1480. let nexts=body.querySelectorAll("a.next");
  1481. for(i=0;i<nexts.length;i++){
  1482. if(!/^([上前首尾][一ー1]?[页頁张張]|previous(\s*page)?\s*›?$|前のページ)/i.test(nexts[i].innerText.trim()) &&
  1483. nexts[i].style.display!=="none" &&
  1484. nexts[i].parentNode.style.display!=="none"){
  1485. next=nexts[i];
  1486. break;
  1487. }
  1488. }
  1489. }
  1490. if(next && (!next.href || /^(javascript|#)/.test(next.href.replace(location.href,"")))){
  1491. jsNext=next;
  1492. next=null;
  1493. }
  1494. if(!next){
  1495. next=body.querySelectorAll("[aria-label='Next page']");
  1496. if(next && next.length==1){
  1497. next=next[0];
  1498. if(!next.href || /^(javascript|#)/.test(next.href.replace(location.href,""))){
  1499. if(!jsNext)jsNext=next;
  1500. next=null;
  1501. }
  1502. }else{
  1503. next=null;
  1504. }
  1505. }
  1506. if(!next){
  1507. next=body.querySelectorAll("[aria-label='Next']");
  1508. if(next && next.length==1){
  1509. next=next[0];
  1510. if(!next.href || /^(javascript|#)/.test(next.href.replace(location.href,""))){
  1511. if(!jsNext)jsNext=next;
  1512. next=null;
  1513. }
  1514. }else{
  1515. next=null;
  1516. }
  1517. }
  1518. if(next && /^[下后後][一ー1]?[章话話篇]/i.test(next.innerText.trim())){
  1519. next2=next;
  1520. next=null;
  1521. }
  1522. if(!next){
  1523. next=body.querySelector("a.curr+a");
  1524. }
  1525. if(!next){
  1526. next=body.querySelector("div.wp-pagenavi>span.current+a,div.page-nav>span.current+a,div.article-paging>span+a");
  1527. }
  1528. if(!next){
  1529. let pageDiv=body.querySelector("div.pages>ul");
  1530. if(pageDiv){
  1531. cur=pageDiv.querySelector("li>b");
  1532. if(cur)next=cur.parentNode.nextElementSibling;
  1533. if(next)next=next.querySelector("a");
  1534. }
  1535. }
  1536. if(!next){
  1537. next=body.querySelector(".number>ul>li.active+li>a");
  1538. }
  1539. if(!next){
  1540. next=body.querySelector(".pages>a[href='javascript:;']+a");
  1541. if(next && (next.href=="javascript:;" || next.getAttribute("href")=="#"))next=null;
  1542. }
  1543. if(!next){
  1544. let pageDiv=body.querySelector(".pagination");
  1545. if(pageDiv){
  1546. cur=pageDiv.querySelector("[class*=current]");
  1547. if(cur)next=cur.parentNode.nextElementSibling;
  1548. if(next)next=next.querySelector("a");
  1549. }
  1550. }
  1551. if(!next){
  1552. let aTags=body.querySelectorAll("a,button,[type='button']");
  1553. for(i=aTags.length-1;i>=0;i--){
  1554. if(next1 && next2 && next3 && next4)break;
  1555. let aTag=aTags[i];
  1556. if(aTag.innerText=="§")continue;
  1557. if(aTag.innerText.length>50)continue;
  1558. if(aTag.style.display=="none")continue;
  1559. if(aTag.href && /next$/i.test(aTag.href))continue;
  1560. if(aTag.className && /slick|slide|gallery/i.test(aTag.className))continue;
  1561. if(aTag.classList && aTag.classList.contains('disabled'))continue;
  1562. if(aTag.parentNode){
  1563. if(aTag.parentNode.className && /slick|slide|gallery/i.test(aTag.parentNode.className))continue;
  1564. if(aTag.parentNode.classList && aTag.parentNode.classList.contains('disabled'))continue;
  1565. if(aTag.parentNode.tagName == "BLOCKQUOTE")continue;
  1566. }
  1567. let innerText = (aTag.innerText||aTag.value||'').replace(/ /g, '');
  1568. let isJs = !aTag.href || /^(javascript|#)/.test(aTag.href.replace(location.href,""));
  1569. if(innerText.length<=18){
  1570. if(!next1){
  1571. if(/^翻?[下后後次][一ー1]?[页頁张張]|^next([ _-]?page)\s*[›>→»]?$|次のページ|^次へ?$/i.test(innerText)){
  1572. if(isJs){
  1573. if(!nextJs1)nextJs1=aTag;
  1574. }else{
  1575. next1=aTag;
  1576. }
  1577. }
  1578. }
  1579. if(!next2){
  1580. if(/^[下后後次][一ー1]?[章话話节節篇个個幅]/i.test(innerText) || /nextpage/i.test(aTag.className) || innerText=="»" || innerText==">>"){
  1581. if(isJs){
  1582. if(!nextJs2)nextJs2=aTag;
  1583. }else{
  1584. next2=aTag;
  1585. }
  1586. }
  1587. }
  1588. if(!next3){
  1589. if(innerText=="Next" || innerText=="next" || innerText=="&gt;" || innerText=="▶" || innerText==">" || innerText=="›" || innerText=="→"){
  1590. if(isJs){
  1591. if(!nextJs3)nextJs3=aTag;
  1592. }else{
  1593. next3=aTag;
  1594. }
  1595. }
  1596. }
  1597. }
  1598. if (isJs) continue;
  1599. if (!next4) {
  1600. let prevEle = aTag.previousElementSibling;
  1601. if (prevEle && (prevEle.tagName == 'B' || prevEle.tagName == 'SPAN' || prevEle.tagName == 'STRONG')) {
  1602. if (/^\d+$/.test(aTag.innerText.trim()) && /^\d+$/.test(prevEle.innerText.trim()) && parseInt(aTag.innerText) == parseInt(prevEle.innerText) + 1) {
  1603. next4 = aTag;
  1604. }
  1605. }
  1606. }
  1607. if (!next4 && aTag.href.length < 250) {
  1608. let _aHref = aTag.href.replace("?&", "?").replace("index.php?", "?");
  1609. let _aHrefTrim = _aHref;
  1610. if (preStr) _aHrefTrim = _aHrefTrim.replace(preStr, "");
  1611. if (afterStr) _aHrefTrim = _aHrefTrim.replace(afterStr, "");
  1612. if ((preStr || afterStr) && pageNum < 999 && _aHrefTrim == pageNum + 1) {
  1613. next4 = aTag;
  1614. } else if (this.curUrl != aTag.href) {
  1615. _aHref = _aHref.replace(/\.s?html?$/i, "");
  1616. if (_aHref.indexOf(_url) != -1 && /^[\/\?&]?[_-]?(p|page)?=?\/?2(\/|\?|&|$)/i.test(_aHref.replace(_url, ""))) {
  1617. let curHref = aTag.getAttribute("href");
  1618. let pageOne = curHref.replace(/\/2(\/|\?|&|$)/,"/1$1");
  1619. if (pageOne == curHref) pageOne = null;
  1620. else pageOne = body.querySelector(`a[href='${pageOne}']`);
  1621. if (!pageOne || pageOne.className != curHref.className) next4 = aTag;
  1622. }
  1623. }
  1624. }
  1625. }
  1626. if(next3){
  1627. let eles=getAllElements(`//a[text()='${next3.innerText}']`, curPage);
  1628. if(eles.length>2)next3=null;
  1629. }
  1630. if(nextJs3){
  1631. let eles=getAllElements(`//a[text()='${nextJs3.innerText}']`, curPage);
  1632. if(eles.length>2)nextJs3=null;
  1633. }
  1634. }
  1635. if (!next) next = next1 || next4 || next3 || next2;
  1636. if (!next && (this.initGetPage || doc != document)) {
  1637. this.initGetPage = false;
  1638. next = jsNext || nextJs1 || nextJs3 || nextJs2;
  1639. if (next && next.parentNode.className.indexOf('tab') != -1) next = null;
  1640. }
  1641. if (next && next.classList && next.classList.contains("results-more")) next=null;
  1642. return {next:next, canSave:canSave};
  1643. }
  1644.  
  1645. canonicalUri(src) {
  1646. if (!src) {
  1647. return "";
  1648. }
  1649. if (src.charAt(0) == "#") return this.curUrl + src;
  1650. if (src.charAt(0) == "?") return this.curUrl.replace(/^([^\?#]+).*/, "$1" + src);
  1651. let origin = location.protocol + '//' + location.host;
  1652. let url = this.basePath || origin;
  1653. url = url.replace(/(\?|#).*/, "");
  1654. if (/https?:\/\/[^\/]+$/.test(url)) url = url + '/';
  1655. if (url.indexOf("http") !== 0) url = origin + url;
  1656. var root_page = /^[^\?#]*\//.exec(url)[0],
  1657. root_domain = /^\w+\:\/\/\/?[^\/]+/.exec(root_page)[0],
  1658. absolute_regex = /^\w+\:\/\//;
  1659. this.updateUrl = false;
  1660. while (src.indexOf("../") === 0) {
  1661. src = src.substr(3);
  1662. root_page = root_page.replace(/\/[^\/]+\/$/, "/");
  1663. this.updateUrl = true;
  1664. }
  1665. src = src.replace(/\.\//, "");
  1666. if (/^\/\/\/?/.test(src)) {
  1667. src = location.protocol + src;
  1668. }
  1669. return (absolute_regex.test(src) ? src : ((src.charAt(0) == "/" ? root_domain : root_page) + src));
  1670. }
  1671.  
  1672. getLinkByPage(url, pageNum) {
  1673. if(!url)return;
  1674. if(this.curSiteRule.pageNum){
  1675. let result=this.curSiteRule.pageNum;
  1676. let strMatch=result.match(/\{.*?}/);
  1677. if(!strMatch)return null;
  1678. let urlReg=new RegExp("("+result.replace(strMatch[0], ")\\d+(")+")","i");
  1679. let code=strMatch[0].replace(/^{/,"").replace(/}$/,"").replace(/\$p/g,pageNum);
  1680. if(code==pageNum){
  1681. result=url.replace(urlReg,"$1"+code+"$2");
  1682. }else{
  1683. try{
  1684. code=Function('"use strict";return ' + code)();
  1685. result=url.replace(urlReg,"$1"+code+"$2");
  1686. }catch(e){
  1687. debug(e);
  1688. }
  1689. }
  1690. if(result!=url){
  1691. return result;
  1692. }
  1693. }
  1694. return url.replace(/([&\/\?](p=|page[=\/_-]?))\d+/i, "$1"+pageNum).replace(/([_-])\d+\./i, "$1"+pageNum+".");
  1695. }
  1696.  
  1697. getPageNumFromUrl(url) {
  1698. if(!url)return curPage;
  1699. if(this.curSiteRule.pageNum){
  1700. let result=this.curSiteRule.pageNum;
  1701. let strMatch=result.match(/\{.*?}/);
  1702. if(!strMatch)return null;
  1703. let urlReg=new RegExp(".*"+result.replace(strMatch[0], "(\\d+)")+".*","i");
  1704. let curShowNum=url.replace(urlReg,"$1");
  1705. if (curShowNum!=url){
  1706. let code=strMatch[0].replace(/^{/,"").replace(/}$/,"");
  1707. if(code=="$p"){
  1708. return curShowNum;
  1709. }else{
  1710. try{
  1711. let page1=Function('"use strict";return ' + code.replace("$p", "0"))();
  1712. let page2=Function('"use strict";return ' + code.replace("$p", "1"))();
  1713. let numGap=page2-page1;
  1714. return (curShowNum - page1) / numGap;
  1715. }catch(e){
  1716. debug(e);
  1717. }
  1718. }
  1719. } else {
  1720. return 1;
  1721. }
  1722. }
  1723. let pageNum=url.replace(/.*[&\/\?](p=|page[=\/_-]?)(\d+).*/i, "$2");
  1724. return pageNum==url?curPage:pageNum;
  1725. }
  1726.  
  1727. async getNextLink(doc) {
  1728. let nextLink = null, page, href;
  1729. let getNextLinkByForm = (form, n) => {
  1730. let params = [];
  1731. let formData = new FormData(form);
  1732. for (let [key, value] of formData) {
  1733. if (n && /^(p|page)$/i.test(key)) {
  1734. params.push(key + '=' + n);
  1735. } else {
  1736. params.push(key + '=' + encodeURIComponent(value));
  1737. }
  1738. }
  1739. params = params.join('&');
  1740. return form.action + (form.action.indexOf('?') == -1 ? '?' : '&') + params + (form.method == 'post' ? '#p{' + params + '}' : '');
  1741. };
  1742. if (this.curSiteRule.pageElementByJs) {
  1743. this.nextLinkHref = "#";
  1744. return true;
  1745. } else if (this.curSiteRule.nextLinkByJs) {
  1746. try {
  1747. let over = _url => {
  1748. };
  1749. let targetUrl = await ((typeof _unsafeWindow.pagetualNextLinkByJs == 'undefined') ? new AsyncFunction("doc", '"use strict";' + this.curSiteRule.nextLinkByJs) : _unsafeWindow.pagetualNextLinkByJs)(doc);
  1750. if (targetUrl) nextLink = {href: targetUrl};
  1751. } catch(e) {
  1752. debug(e);
  1753. }
  1754. } else if (this.curSiteRule.nextLinkByUrl) {
  1755. let targetUrl = this.curUrl.replace(new RegExp(this.curSiteRule.nextLinkByUrl[0], "i"), this.curSiteRule.nextLinkByUrl[1]);
  1756. if (targetUrl != this.curUrl) {
  1757. let includeSel = this.curSiteRule.nextLinkByUrl[2];
  1758. let excludeSel = this.curSiteRule.nextLinkByUrl[3];
  1759. if (includeSel) {
  1760. includeSel = includeSel.trim();
  1761. if (!getElement(includeSel, doc)) {
  1762. this.nextLinkHref=false;
  1763. return null;
  1764. }
  1765. }
  1766. if (excludeSel) {
  1767. excludeSel = excludeSel.trim();
  1768. if (getElement(excludeSel, doc)) {
  1769. this.nextLinkHref=false;
  1770. return null;
  1771. }
  1772. }
  1773. let reps = targetUrl.match(/{.*?}/g);
  1774. if (reps) {
  1775. reps.forEach(rep => {
  1776. let code = rep.replace("{","").replace("}", "").replace(/\(\)/g, "0");
  1777. let result = code.match(/^(\d*)\+1$/);
  1778. if (result) {
  1779. result = parseInt(result[1] || 1) + 1;
  1780. } else {
  1781. try {
  1782. result = Function('"use strict";return ' + code)();
  1783. } catch(e) {
  1784. debug(e);
  1785. }
  1786. }
  1787. targetUrl = targetUrl.replace(rep, result);
  1788. });
  1789. }
  1790. }
  1791. nextLink = {href: targetUrl};
  1792. } else if (this.curSiteRule.nextLink) {
  1793. let nextLinkSel = this.curSiteRule.nextLink;
  1794. if (nextLinkSel != "0" && nextLinkSel != 0) {
  1795. if (Array && Array.isArray && Array.isArray(nextLinkSel)) {
  1796. nextLink = getElement(nextLinkSel[nextIndex], doc);
  1797. } else nextLink = getElement(nextLinkSel, doc);
  1798. }
  1799. if (nextLink && (this.curSiteRule.action == 0 || this.curSiteRule.action == 1 || this.curSiteRule.action == 2)) {
  1800. let form = doc.querySelector('#search-form');
  1801. if (!nextLink.href && nextLink.hasAttribute("onclick") && form) {
  1802. if (/^\d+$/.test(nextLink.innerText)) {
  1803. nextLink.href = getNextLinkByForm(form, nextLink.innerText);
  1804. }
  1805. } else if (nextLink.tagName == "INPUT" || nextLink.type == "submit") {
  1806. form = nextLink.parentNode;
  1807. while (form) {
  1808. if (form.tagName == "FORM") break;
  1809. else form = form.parentNode;
  1810. }
  1811. if (form) {
  1812. nextLink.href = getNextLinkByForm(form);
  1813. }
  1814. }
  1815. if (nextLink.href && this.curSiteRule.action != 0) {
  1816. nextLink.href = nextLink.href.replace(/#p{.*/, "");
  1817. }
  1818. }
  1819. }else{
  1820. page=this.getPage(doc);
  1821. nextLink=page.next;
  1822. if(nextLink){
  1823. if(nextLink.tagName=="INPUT" || nextLink.type=="submit"){
  1824. let form = nextLink.parentNode;
  1825. while (form) {
  1826. if (form.tagName == "FORM") break;
  1827. else form = form.parentNode;
  1828. }
  1829. if (form) {
  1830. nextLink.href = getNextLinkByForm(form);
  1831. }
  1832. }
  1833. let parent = nextLink;
  1834. while (parent && parent.tagName !== "BODY") {
  1835. if (parent.hasAttribute("disabled")) {
  1836. this.nextLinkHref = false;
  1837. return null;
  1838. }
  1839. if (parent.className && parent.classList) {
  1840. if (parent.classList.contains("noClick") || /slick|slide/i.test(parent.className)) {
  1841. this.nextLinkHref = false;
  1842. return null;
  1843. }
  1844. }
  1845. if (parent.style.display === "none") {
  1846. this.nextLinkHref = false;
  1847. return null;
  1848. }
  1849. parent = parent.parentNode;
  1850. }
  1851. if(doc==document){
  1852. if((!nextLink.href || /^(javascript|#)/.test(nextLink.href.replace(location.href,""))) && !isVisible(nextLink, _unsafeWindow)){
  1853. this.nextLinkHref=false;
  1854. return null;
  1855. }else{
  1856. let nextLinkCs=_unsafeWindow.getComputedStyle(nextLink);
  1857. if(nextLinkCs.cursor=="not-allowed"){
  1858. this.nextLinkHref=false;
  1859. return null;
  1860. }
  1861. this.initNext=nextLink;
  1862. }
  1863. }
  1864. let form=doc.querySelector('#search-form');
  1865. if(!nextLink.href && nextLink.hasAttribute("onclick") && form){
  1866. if(form && /^\d+$/.test(nextLink.innerText)){
  1867. href=getNextLinkByForm(form, nextLink.innerText);
  1868. }
  1869. }
  1870. }
  1871. }
  1872. if (nextLink) {
  1873. if (this.curSiteRule.stopSign) {
  1874. if (Array && Array.isArray && Array.isArray(this.curSiteRule.stopSign)) {
  1875. let includeSel = this.curSiteRule.stopSign[0];
  1876. let excludeSel = this.curSiteRule.stopSign[1];
  1877. let curSign = this.curSiteRule.stopSign[2];
  1878. let maxSign = this.curSiteRule.stopSign[3];
  1879. if (Array && Array.isArray && Array.isArray(includeSel) && !curSign) {
  1880. curSign = includeSel;
  1881. includeSel = false;
  1882. }
  1883. if (Array && Array.isArray && Array.isArray(excludeSel) && !maxSign) {
  1884. maxSign = excludeSel;
  1885. excludeSel = false;
  1886. }
  1887. if (includeSel) {
  1888. includeSel = includeSel.trim();
  1889. if (!getElement(includeSel, doc)) {
  1890. this.nextLinkHref=false;
  1891. return null;
  1892. }
  1893. }
  1894. if (excludeSel) {
  1895. excludeSel = excludeSel.trim();
  1896. if (getElement(excludeSel, doc)) {
  1897. this.nextLinkHref=false;
  1898. return null;
  1899. }
  1900. }
  1901. if (curSign && maxSign) {
  1902. let currentEle = getElement(curSign[0], doc);
  1903. let maxEle = getElement(maxSign[0], doc);
  1904. if (currentEle && maxEle) {
  1905. let currentSignNum, maxSignNum;
  1906. if (/\(.*\)/.test(curSign[1])) {
  1907. currentSignNum = currentEle.innerText.match(new RegExp(curSign[1]));
  1908. if (currentSignNum) currentSignNum = currentSignNum[1];
  1909. } else if (currentEle.getAttribute) {
  1910. currentSignNum = currentEle.getAttribute(curSign[1]);
  1911. }
  1912. if (/\(.*\)/.test(maxSign[1])) {
  1913. maxSignNum = maxEle.innerText.match(new RegExp(maxSign[1]));
  1914. if (maxSignNum) maxSignNum = maxSignNum[1];
  1915. } else if (maxEle.getAttribute) {
  1916. maxSignNum = maxEle.getAttribute(maxSign[1]);
  1917. }
  1918. if (currentSignNum && maxSignNum && currentSignNum == maxSignNum) {
  1919. this.nextLinkHref = false;
  1920. return null;
  1921. }
  1922. }
  1923. }
  1924. } else {
  1925. try {
  1926. let stopSign = ((typeof _unsafeWindow.stopSign == 'undefined') ? Function("doc", "nextLink", '"use strict";' + this.curSiteRule.stopSign) : _unsafeWindow.stopSign)(doc, nextLink);
  1927. if (stopSign) {
  1928. this.nextLinkHref = false;
  1929. return null;
  1930. }
  1931. } catch(e) {
  1932. debug(e);
  1933. }
  1934. }
  1935. }
  1936. if (this.curSiteRule.action == 3) {
  1937. if (doc == document) debug(nextLink, 'Next link');
  1938. this.nextLinkHref = '#';
  1939. } else {
  1940. let needUrl = (this.curSiteRule.action == 0 || this.curSiteRule.action == 1 || this.curSiteRule.action == 2);
  1941. if (!href) href = nextLink.href;
  1942. if (href && nextLink.getAttribute) {
  1943. let _href = nextLink.getAttribute("href");
  1944. if (_href) {
  1945. if (_href.charAt(0) == "#" || _href == "?"){
  1946. href = "#";
  1947. } else {
  1948. href = _href;
  1949. }
  1950. }
  1951. }
  1952.  
  1953. if(needUrl && (href===""||href===null)){
  1954. this.nextLinkHref=false;
  1955. }else if(needUrl && /^(javascript:|#)/.test(href)){
  1956. this.nextLinkHref=false;
  1957. }else{
  1958. this.nextLinkHref=(href && !/^(javascript:|#)/.test(href))?this.canonicalUri(href):"#";
  1959. if(this.nextLinkHref!="#" && (this.nextLinkHref==this.curUrl || this.nextLinkHref==this.curUrl+"#" || this.nextLinkHref==this.oldUrl || this.nextLinkHref==this.oldUrl+"#")){
  1960. this.nextLinkHref=false;
  1961. }else if(doc==document)debug(nextLink, 'Next link');
  1962. }
  1963. }
  1964. }else{
  1965. this.nextLinkHref=false;
  1966. }
  1967. this.preload();
  1968. return nextLink;
  1969. }
  1970.  
  1971. preload(){
  1972. if(!rulesData.preload)return;
  1973. if(!this.nextLinkHref || this.nextLinkHref=="#")return;
  1974. let self=this;
  1975. _GM_xmlhttpRequest({
  1976. url: this.nextLinkHref,
  1977. method: 'GET',
  1978. overrideMimeType: 'text/html;charset=' + (document.characterSet || document.charset || document.inputEncoding),
  1979. headers: {
  1980. 'Referer': location.href
  1981. },
  1982. timeout: 10000,
  1983. onload: function(res) {
  1984. var doc=null;
  1985. try {
  1986. doc=document.implementation.createHTMLDocument('');
  1987. doc.documentElement.innerHTML=res.response;
  1988. var body = doc.body;
  1989. if (body && body.firstChild) {
  1990. self.lazyImgAction(body.children);
  1991. }
  1992. if(!self.preloadDiv){
  1993. self.preloadDiv = document.createElement('div');
  1994. self.preloadDiv.id = "pagetual-preload";
  1995. self.preloadDiv.style.cssText = 'display:none!important;';
  1996. document.body.appendChild(self.preloadDiv);
  1997. self.checkedImgs={};
  1998. }
  1999. [].forEach.call(doc.images, i=>{
  2000. let iSrc=i.src;
  2001. if(iSrc && !self.checkedImgs[iSrc]){
  2002. self.checkedImgs[iSrc] = true;
  2003. let img = document.createElement('img');
  2004. img.src = iSrc;
  2005. self.preloadDiv.appendChild(img);
  2006. }
  2007. });
  2008. }
  2009. catch (e) {
  2010. return;
  2011. }
  2012. }
  2013. });
  2014. }
  2015.  
  2016. getInsert(refresh) {
  2017. if(refresh){
  2018. this.insert=null;
  2019. }
  2020. if(this.insert && document.documentElement.contains(this.insert)){
  2021. return this.insert;
  2022. }
  2023. if (this.curSiteRule.insert) {
  2024. let insertSel = this.curSiteRule.insert;
  2025. if (Array && Array.isArray && Array.isArray(insertSel)) {
  2026. insertSel = insertSel[nextIndex < insertSel.length ? nextIndex : 0];
  2027. }
  2028. this.insert=getElement(insertSel, document);
  2029. } else {
  2030. let pageElement = this.getPageElement(document, _unsafeWindow);
  2031. if (this.curSiteRule.singleUrl && this.nextLinkHref == "#" && this.curSiteRule.pageElement === 'body') {
  2032. debug("Stop as jsNext & whole body");
  2033. isPause = true;
  2034. return null;
  2035. }
  2036. if (pageElement && pageElement.length > 0) {
  2037. var pELast = pageElement[pageElement.length - 1];
  2038. this.insert = pELast.nextSibling ? pELast.nextSibling : pELast.parentNode.appendChild(document.createTextNode(' '));
  2039. }
  2040. }
  2041. return this.insert;
  2042. }
  2043.  
  2044. pageInit(doc,eles){
  2045. let code=this.curSiteRule.pageInit;
  2046. if(code){
  2047. let initFunc=((typeof _unsafeWindow.pagetualPageInit=='undefined') ? Function("doc", "eles", '"use strict";' + code) : _unsafeWindow.pagetualPageInit);
  2048. let checkInit=(resolve)=>{
  2049. try{
  2050. if(initFunc(doc, eles)===false){
  2051. setTimeout(()=>{
  2052. checkInit(resolve);
  2053. },100);
  2054. } else {
  2055. resolve(true);
  2056. }
  2057. }catch(e){
  2058. resolve(false);
  2059. debug(e);
  2060. }
  2061. };
  2062. return new Promise((resolve) => {
  2063. checkInit(function(e) {
  2064. resolve(e)
  2065. });
  2066. })
  2067. }
  2068. }
  2069.  
  2070. pageAction(doc,eles){
  2071. let code=this.curSiteRule.pageAction;
  2072. if(code){
  2073. try{
  2074. ((typeof _unsafeWindow.pagetualPageAction=='undefined') ? Function("doc", "eles", '"use strict";' + code) : _unsafeWindow.pagetualPageAction)(doc, eles);
  2075. }catch(e){
  2076. debug(e);
  2077. }
  2078. }
  2079. this.openInNewTab(eles);
  2080. this.replaceElement(doc);
  2081. }
  2082.  
  2083. openInNewTab(eles){
  2084. if(rulesData.openInNewTab){
  2085. [].forEach.call(eles, ele=>{
  2086. if(ele.tagName=="A" && ele.href && !/^(mailto:|javascript:)|#/.test(ele.href)){
  2087. ele.setAttribute('target', '_blank');
  2088. }else{
  2089. [].forEach.call(ele.querySelectorAll('a[href]:not([href^="mailto:"]):not([href^="javascript:"]):not([href^="#"])'), a=>{
  2090. a.setAttribute('target', '_blank');
  2091. if (a.getAttribute('onclick') == 'atarget(this)') {
  2092. a.removeAttribute('onclick');
  2093. }
  2094. });
  2095. }
  2096. });
  2097. }
  2098. }
  2099.  
  2100. lazyImgAction(eles) {
  2101. if (!eles || eles.length == 0) return;
  2102. let lazyImgSrc = this.curSiteRule.lazyImgSrc;
  2103. if (lazyImgSrc === 0 || lazyImgSrc === '0') return;
  2104. let setLazyImg = img => {
  2105. let realSrc;
  2106. if (lazyImgSrc) {
  2107. if (!Array.isArray(lazyImgSrc)) {
  2108. lazyImgSrc = [lazyImgSrc];
  2109. }
  2110. realSrc = img.getAttribute(lazyImgSrc[0]);
  2111. if (lazyImgSrc.length == 2) {
  2112. let removeProps = lazyImgSrc[1].split(",");
  2113. removeProps.forEach(prop => {
  2114. img.removeAttribute(prop.trim());
  2115. });
  2116. }
  2117. }
  2118. if (!realSrc) {
  2119. if (img.getAttribute("_src") && !img.src) {
  2120. realSrc = img.getAttribute("_src");
  2121. } else if (img.dataset) {
  2122. if (img.dataset.original) {
  2123. realSrc = img.dataset.original;
  2124. } else if (img.dataset.lazySrc) {
  2125. realSrc = img.dataset.lazySrc;
  2126. } else if (img.dataset.lazy) {
  2127. realSrc = img.dataset.lazy;
  2128. } else if (img.dataset.src) {
  2129. realSrc = img.dataset.src;
  2130. } else if (img.dataset.origFile) {
  2131. realSrc = img.dataset.origFile;
  2132. }
  2133. }
  2134. if (!realSrc && img._lazyrias && img._lazyrias.srcset) {
  2135. realSrc = img._lazyrias.srcset[img._lazyrias.srcset.length - 1];
  2136. }
  2137. if (realSrc) {
  2138. img.removeAttribute("srcset");
  2139. } else if (img.srcset) {
  2140. var srcs = img.srcset.split(/[xw],/), largeSize = 0;
  2141. srcs.forEach(srci => {
  2142. let srcInfo = srci.trim().split(" "), curSize = parseInt(srcInfo[1]);
  2143. if (srcInfo[1] && curSize > largeSize) {
  2144. largeSize = curSize;
  2145. realSrc = srcInfo[0];
  2146. }
  2147. });
  2148. }
  2149. }
  2150. if (realSrc) {
  2151. img.src = realSrc;
  2152. if (img.style.display == "none") {
  2153. img.style.display = "";
  2154. }
  2155. if (img.style.visibility == "hidden") {
  2156. img.style.visibility = "";
  2157. }
  2158. if (img.style.opacity == 0) {
  2159. img.style.opacity = "";
  2160. }
  2161. }
  2162. };
  2163. [].forEach.call(eles, ele=>{
  2164. if(ele.tagName=="IMG"){
  2165. setLazyImg(ele);
  2166. }else{
  2167. [].forEach.call(ele.querySelectorAll("img"), img=>{
  2168. setLazyImg(img);
  2169. });
  2170. [].forEach.call(ele.querySelectorAll("div[data-src][data-thumb]"), div=>{
  2171. div.style.setProperty("background-image", "url("+div.dataset.src+")", "important");
  2172. });
  2173. }
  2174. if(ele.tagName=="A" && ele.classList.contains("lazyload")){
  2175. if(ele.dataset.original){
  2176. ele.style.backgroundImage='url("'+ele.dataset.original+'")';
  2177. }
  2178. }else{
  2179. [].forEach.call(ele.querySelectorAll("a.lazyload"), a=>{
  2180. if(a.dataset.original){
  2181. a.style.backgroundImage='url("'+a.dataset.original+'")';
  2182. }
  2183. });
  2184. }
  2185. });
  2186. }
  2187.  
  2188. initPage(callback){
  2189. let self=this;
  2190. curPage=1;
  2191. //if(this.curSiteRule.url && !this.curSiteRule.singleUrl)return;
  2192. this.curSiteRule={};
  2193. this.pageDoc=document;
  2194. this.nextLinkHref=null;
  2195. this.curUrl=location.href;
  2196. let base=document.querySelector("base");
  2197. this.basePath=base?base.href:location.href;
  2198. this.getRule(async () => {
  2199. if(self.curSiteRule.enable==0){
  2200. debug("Stop as rule disable");
  2201. isPause=true;
  2202. return;
  2203. }
  2204. //若是再亂匹配就不緩存wedata,或者只在找完本地規則之後再考慮wedata的緩存
  2205. if (self.curSiteRule.singleUrl) {
  2206. self.curSiteRule.pageElement = "";
  2207. self.smartRules = self.smartRules.filter(item => {return item && item.url != self.curSiteRule.url});
  2208. self.smartRules.unshift(self.curSiteRule);
  2209. if (self.smartRules.length > 100) {
  2210. self.smartRules.pop();
  2211. }
  2212. storage.setItem("smartRules", self.smartRules);
  2213. } else if (self.curSiteRule && self.curSiteRule.url.length > 13) {
  2214. self.hpRules = self.hpRules.filter(item => {return item && item.url != self.curSiteRule.url});
  2215. self.hpRules.unshift(self.curSiteRule);
  2216. if (self.hpRules.length > 30) {
  2217. self.hpRules.pop();
  2218. }
  2219. storage.setItem("hpRules", self.hpRules);
  2220. }
  2221. let css=self.curSiteRule.css || rulesData.customCss;
  2222. if(css && !/^inIframe:/.test(css)){
  2223. _GM_addStyle(css);
  2224. }
  2225. let autoClick=self.curSiteRule.autoClick;
  2226. if(autoClick){
  2227. let autoClickBtn;
  2228. autoClickBtn=getElement(autoClick, document);
  2229. if(autoClickBtn){
  2230. emuClick(autoClickBtn);
  2231. }
  2232. }
  2233. let code=self.curSiteRule.init;
  2234. if(code){
  2235. try{
  2236. ((typeof _unsafeWindow.pagetualInit=='undefined') ? Function('doc','win','iframe','"use strict";' + code) : _unsafeWindow.pagetualInit)(null,null,null);
  2237. }catch(e){
  2238. debug(e);
  2239. }
  2240. }
  2241. await self.getNextLink(document);
  2242. self.refreshByClick();
  2243. callback();
  2244. });
  2245. }
  2246.  
  2247. insertElement(ele) {
  2248. this.getInsert();
  2249. if(this.curSiteRule.insertPos==2){
  2250. this.insert.appendChild(ele);
  2251. }else{
  2252. this.insert.parentNode.insertBefore(ele, this.insert);
  2253. }
  2254. }
  2255.  
  2256. async insertPage(doc, eles, url, callback, tried) {
  2257. this.oldUrl=this.curUrl;
  2258. let oldTitle=this.pageDoc.title;
  2259. this.pageDoc=doc;
  2260. this.curUrl=url;
  2261. let nextLink=await this.getNextLink(doc);
  2262. this.nextTitle="";
  2263. if(this.curSiteRule.pageBarText){
  2264. if(this.curSiteRule.pageBarText==1 || this.curSiteRule.pageBarText==true){
  2265. this.nextTitle=doc.title;
  2266. }else{
  2267. try{
  2268. this.nextTitle=((typeof _unsafeWindow.pagetualPageBarText=='undefined') ? Function("doc",'"use strict";' + this.curSiteRule.pageBarText) : _unsafeWindow.pagetualPageBarText)(doc);
  2269. }catch(e){
  2270. debug(e);
  2271. }
  2272. }
  2273. }
  2274. if(curPage==1 && !tried && !nextLink && this.curSiteRule.singleUrl && this.curSiteRule.pageElement && this.curSiteRule.action!=0){
  2275. this.curSiteRule.action=1;
  2276. this.curUrl=location.href;
  2277. return false;
  2278. }
  2279. if(callback)callback(eles);
  2280. this.getInsert();
  2281. var self=this,newEles=[];
  2282. if(!eles || eles.length==0 || !self.insert || !self.insert.parentNode){
  2283. }else{
  2284. isLoading=true;
  2285. await this.pageInit(doc, eles);
  2286. let curScroll=document.body.scrollTop||document.documentElement.scrollTop;
  2287. [].forEach.call(eles, ele=>{
  2288. let newEle=ele.cloneNode(true);
  2289. let oldCanvass=ele.querySelectorAll("canvas");
  2290. let newCanvass=newEle.querySelectorAll("canvas");
  2291. if(self.updateUrl){
  2292. [].forEach.call(newEle.querySelectorAll("img"), img=>{
  2293. if (img.getAttribute("src")) img.src=self.canonicalUri(img.getAttribute("src"));
  2294. });
  2295. [].forEach.call(newEle.querySelectorAll("a"), a=>{
  2296. if (a.getAttribute("href")) a.href = self.canonicalUri(a.getAttribute("href"));
  2297. });
  2298. }
  2299. for(let i=0;i<oldCanvass.length;i++){
  2300. let oldCanvas=oldCanvass[i];
  2301. let newCanvas=newCanvass[i];
  2302. newCanvas.getContext('2d').drawImage(oldCanvas, 0, 0);
  2303. }
  2304. self.insertElement(newEle);
  2305. newEles.push(newEle);
  2306. });
  2307. document.body.scrollTop=curScroll;
  2308. document.documentElement.scrollTop=curScroll;
  2309. }
  2310. this.pageAction(doc, newEles);
  2311. let enableHistory = this.curSiteRule.history;
  2312. let enableHistoryAfterInsert = false;
  2313. if (enableHistory == 1) {
  2314. enableHistory = true;
  2315. } else if (enableHistory == 2) {
  2316. enableHistory = true;
  2317. enableHistoryAfterInsert = true;
  2318. } else if (enableHistory == 0) {
  2319. enableHistory = false;
  2320. } else {
  2321. enableHistory = rulesData.enableHistory;
  2322. enableHistoryAfterInsert = rulesData.enableHistoryAfterInsert;
  2323. }
  2324. if (enableHistory) {
  2325. let historyUrl = enableHistoryAfterInsert ? this.curUrl : this.oldUrl;
  2326. if(historyUrl != location.href) {
  2327. let isJs=/^(javascript|#)/.test(historyUrl.replace(location.href, ""));
  2328. if(!isJs){
  2329. let historyTitle = enableHistoryAfterInsert ? doc.title : oldTitle;
  2330. _unsafeWindow.history.replaceState(undefined, historyTitle, historyUrl);
  2331. document.title = historyTitle;
  2332. }
  2333. }
  2334. }
  2335. isLoading = false;
  2336. return true;
  2337. }
  2338. }
  2339. var ruleParser = new RuleParser();
  2340.  
  2341. class NextSwitch {
  2342. static nextSwitch;
  2343. constructor() {
  2344. this.init();
  2345. }
  2346.  
  2347. static getInstance() {
  2348. if (!NextSwitch.nextSwitch) {
  2349. NextSwitch.nextSwitch = new NextSwitch();
  2350. }
  2351. return NextSwitch.nextSwitch;
  2352. }
  2353.  
  2354. init() {
  2355. let self = this;
  2356. let cssText = `
  2357. #pagetual-nextSwitch {
  2358. position: fixed;
  2359. top: 10px;
  2360. left: calc(50% - 160px);
  2361. background: aliceblue;
  2362. padding: 10px;
  2363. border-radius: 5px;
  2364. text-align: center;
  2365. opacity: 0.95;
  2366. color: #161616;
  2367. z-index: 2147483647;
  2368. font-size: 16px;
  2369. box-shadow: rgb(0 0 0) 0px 0px 10px;
  2370. }
  2371. #pagetual-nextSwitch>.title {
  2372. margin: -5px 45px 10px 45px;
  2373. font-size: 20px;
  2374. font-weight: bold;
  2375. border-bottom: 1px solid black;
  2376. user-select: none;
  2377. color: orangered;
  2378. }
  2379. #pagetual-nextSwitch>.group {
  2380. display: flex;
  2381. flex-direction: column;
  2382. }
  2383. #pagetual-nextSwitch>.group>span {
  2384. color: #161616;
  2385. cursor: pointer;
  2386. margin: 3px;
  2387. font-size: larger;
  2388. }
  2389. #pagetual-nextSwitch>.group>span:hover {
  2390. color: red;
  2391. }
  2392. #pagetual-nextSwitch>.group>span.current {
  2393. border: 2px dotted red;
  2394. border-radius: 10px;
  2395. }
  2396. #pagetual-nextSwitch>.closeSwitch {
  2397. position: absolute;
  2398. top: 3px;
  2399. right: 10px;
  2400. background: none;
  2401. border: none;
  2402. vertical-align: top;
  2403. transition: transform .15s ease-in-out;
  2404. float: right;
  2405. cursor: pointer;
  2406. }
  2407. #pagetual-nextSwitch svg {
  2408. width: 30px;
  2409. height: 30px;
  2410. vertical-align: middle;
  2411. fill: #161616;
  2412. overflow: hidden;
  2413. }
  2414. #pagetual-nextSwitch button:hover {
  2415. transform: scale(1.2);
  2416. }
  2417. `;
  2418. _GM_addStyle(cssText);
  2419. let frame = document.createElement("div");
  2420. frame.id = "pagetual-nextSwitch";
  2421. frame.innerHTML = createHTML(`
  2422. <div class="title">${i18n("nextSwitch")}</div>
  2423. <button type="button" class="closeSwitch">
  2424. <svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2754">
  2425. <path d="M512 128c212 0 384 172 384 384s-172 384-384 384-384-172-384-384 172-384 384-384m0-64C264.8 64 64 264.8 64 512s200.8 448 448 448 448-200.8 448-448S759.2 64 512 64z m238.4 254.4l-45.6-45.6L512 467.2 318.4 273.6l-45.6 45.6L467.2 512 273.6 705.6l45.6 45.6L512 557.6l193.6 193.6 45.6-45.6L557.6 512l192.8-193.6z" p-id="2755">
  2426. </path>
  2427. </svg>
  2428. </button>
  2429. <div class="group"></div>
  2430. `);
  2431. let group = frame.querySelector(".group");
  2432. let closeBtn = frame.querySelector(".closeSwitch");
  2433. closeBtn.addEventListener("click", e => {
  2434. self.close();
  2435. }, true);
  2436. this.frame = frame;
  2437. let currentSpan;
  2438. ruleParser.curSiteRule.nextLink.forEach((link, i) => {
  2439. let span = document.createElement("span");
  2440. let target = getElement(link, document);
  2441. let index = "<b>" + (i + 1) + "</b>: ";
  2442. if (target) {
  2443. let targetInner = target.innerText.trim();
  2444. span.innerHTML = index + (targetInner || link);
  2445. } else {
  2446. span.innerHTML = index + "Not Found";
  2447. }
  2448. span.title = link;
  2449. span.addEventListener("click", e => {
  2450. if (currentSpan) currentSpan.classList.remove("current");
  2451. span.classList.add("current");
  2452. currentSpan = span;
  2453. nextIndex = i;
  2454. storage.setItem("nextSwitch_" + location.host, nextIndex === 0 ? "" : nextIndex);
  2455. ruleParser.curUrl += "#pagetual";
  2456. ruleParser.oldUrl = ruleParser.curUrl;
  2457. autoLoadNum = -1;
  2458. if (!ruleParser.nextLinkHref) {
  2459. isLoading = false;
  2460. }
  2461. ruleParser.getNextLink(ruleParser.pageDoc || document);
  2462. self.close();
  2463. }, true);
  2464. if (i == nextIndex) {
  2465. span.classList.add("current");
  2466. currentSpan = span;
  2467. }
  2468. group.appendChild(span);
  2469. });
  2470. }
  2471.  
  2472. start() {
  2473. document.documentElement.appendChild(this.frame);
  2474. }
  2475.  
  2476. close() {
  2477. if (this.frame.parentNode) this.frame.parentNode.removeChild(this.frame);
  2478. }
  2479. }
  2480.  
  2481. class Picker {
  2482. static picker;
  2483. constructor() {
  2484. this.init();
  2485. }
  2486.  
  2487. static getInstance() {
  2488. if (!Picker.picker) {
  2489. Picker.picker = new Picker();
  2490. }
  2491. return Picker.picker;
  2492. }
  2493.  
  2494. init() {
  2495. let self = this;
  2496. this.signList = [];
  2497. let cssText = `
  2498. body.pagetual-picker,
  2499. body.pagetual-picker *:hover,
  2500. body.pagetual-picker a:hover {
  2501. cursor: crosshair !important;
  2502. }
  2503. #pagetual-picker {
  2504. position: fixed;
  2505. top: 10px;
  2506. left: calc(50% - 178px);
  2507. background: aliceblue;
  2508. padding: 10px;
  2509. border-radius: 5px;
  2510. text-align: center;
  2511. opacity: 0.95;
  2512. color: #161616;
  2513. z-index: 2147483647;
  2514. font-size: 16px;
  2515. box-shadow: rgb(0 0 0) 0px 0px 10px;
  2516. }
  2517. #pagetual-picker>.title {
  2518. margin: -5px 45px 10px 45px;
  2519. font-size: 20px;
  2520. font-weight: bold;
  2521. cursor: move;
  2522. border-bottom: 1px solid black;
  2523. user-select: none;
  2524. color: orangered;
  2525. font-family: Times New Roman;
  2526. }
  2527. #pagetual-picker button {
  2528. background: none;
  2529. border: none;
  2530. vertical-align: top;
  2531. transition: transform .15s ease-in-out;
  2532. float: right;
  2533. cursor: pointer;
  2534. }
  2535. #pagetual-picker button:hover {
  2536. transform: scale(1.2);
  2537. }
  2538. #pagetual-picker>.closePicker {
  2539. position: absolute;
  2540. top: 3px;
  2541. right: 10px;
  2542. }
  2543. #pagetual-picker>.logoToHome {
  2544. position: absolute;
  2545. top: 3px;
  2546. left: 10px;
  2547. }
  2548. #pagetual-picker .selector{
  2549. display: inline-block;
  2550. width: 290px;
  2551. height: 20px;
  2552. max-width: calc(65vw - 50px);
  2553. padding: 6px 12px;
  2554. font-size: 16px;
  2555. font-weight: 400;
  2556. line-height: 1.5;
  2557. color: #495057;
  2558. background-color: #fff;
  2559. background-clip: padding-box;
  2560. border: 1px solid #ced4da;
  2561. border-radius: 4px;
  2562. transition: border-color .15s ease-in-out,box-shadow .15s ease-in-out;
  2563. box-sizing: content-box;
  2564. }
  2565. #pagetual-picker .selector:focus {
  2566. color: #495057;
  2567. background-color: #fff;
  2568. border-color: #80bdff;
  2569. outline: 0;
  2570. box-shadow: 0 0 0 3.2px rgb(0 123 255 / 25%);
  2571. }
  2572. #pagetual-picker [type=checkbox],
  2573. #pagetual-picker [type=radio] {
  2574. line-height: 20px;
  2575. height: 25px;
  2576. width: 25px;
  2577. margin-left: 5px;
  2578. vertical-align: middle;
  2579. appearance: auto;
  2580. display: inline-block;
  2581. }
  2582. #pagetual-picker label {
  2583. font-size: 18px;
  2584. line-height: 25px;
  2585. vertical-align: middle;
  2586. display: inline-block;
  2587. color: black;
  2588. }
  2589. #pagetual-picker .bottom {
  2590. text-align: left;
  2591. margin: 10px 0;
  2592. width: 100%;
  2593. }
  2594. #pagetual-picker .bottom>button {
  2595. float: right;
  2596. }
  2597. #pagetual-picker svg {
  2598. width: 30px;
  2599. height: 30px;
  2600. vertical-align: middle;
  2601. fill: #161616;
  2602. overflow: hidden;
  2603. }
  2604. #pagetual-picker .allpath {
  2605. font-size: 18px;
  2606. margin: 10px;
  2607. max-width: 350px;
  2608. word-break: break-all;
  2609. cursor: context-menu;
  2610. overflow: hidden;
  2611. max-height: 42px;
  2612. -moz-transition:max-height 1s ease-in;
  2613. -webkit-transition:max-height 1s ease-in;
  2614. transition:max-height 1s ease-in;
  2615. color: black;
  2616. }
  2617. #pagetual-picker .allpath:hover {
  2618. max-height: calc(100vh - 130px);
  2619. overflow: auto;
  2620. }
  2621. #pagetual-picker .allpath>span.path {
  2622. cursor: pointer;
  2623. }
  2624. #pagetual-picker .allpath>span.path:hover {
  2625. color: orangered;
  2626. }
  2627. #pagetual-picker .moreConfig {
  2628. display: flex;
  2629. justify-content: space-between;
  2630. border-top: 1px solid;
  2631. padding-top: 10px;
  2632. width: 100%;
  2633. }
  2634. #pagetual-picker .command {
  2635. width: 100%;
  2636. color: black;
  2637. text-align: center;
  2638. font-size: large;
  2639. margin-top: 10px;
  2640. }
  2641. #pagetual-picker .command:hover {
  2642. color: orangered;
  2643. }
  2644. `;
  2645. _GM_addStyle(cssText);
  2646. this.mainSignDiv = this.createSignDiv();
  2647. this.allSignDiv = [];
  2648. let frame = document.createElement("div");
  2649. frame.id = "pagetual-picker";
  2650. frame.innerHTML = createHTML(`
  2651. <button title="Pagetual" type="button" class="logoToHome">
  2652. <svg width="30" height="30" class="upSvg pagetual" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"><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"></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"></path></svg>
  2653. </button>
  2654. <div class="title">${i18n("picker")}</div>
  2655. <button title="${i18n("closePicker")}" type="button" class="closePicker">
  2656. <svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"><path d="M512 128c212 0 384 172 384 384s-172 384-384 384-384-172-384-384 172-384 384-384m0-64C264.8 64 64 264.8 64 512s200.8 448 448 448 448-200.8 448-448S759.2 64 512 64z m238.4 254.4l-45.6-45.6L512 467.2 318.4 273.6l-45.6 45.6L467.2 512 273.6 705.6l45.6 45.6L512 557.6l193.6 193.6 45.6-45.6L557.6 512l192.8-193.6z" fill="#604b4a"></path></svg>
  2657. </button>
  2658. <div class="allpath" title="${i18n("switchSelector")}"></div>
  2659. <div>
  2660. <textarea class="selector" spellcheck="false" name="selector" placeholder="${i18n("pickerPlaceholder")}"></textarea>
  2661. <button id="check" title="${i18n("pickerCheck")}" type="button">
  2662. <svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"><path d="M512 128a384 384 0 1 0 0 768 384 384 0 0 0 0-768z m0-85.333333c259.2 0 469.333333 210.133333 469.333333 469.333333s-210.133333 469.333333-469.333333 469.333333S42.666667 771.2 42.666667 512 252.8 42.666667 512 42.666667zM696.149333 298.666667L768 349.866667 471.594667 725.333333 256 571.733333l53.888-68.266666 143.744 102.4z" fill="#604b4a"></path></svg>
  2663. </button>
  2664. </div>
  2665. <div class="bottom">
  2666. <input name="xpath" id="checkbox_id" type="checkbox">
  2667. <label for="checkbox_id">XPath</label>
  2668. <button id="edit" title="${i18n("gotoEdit")}" type="button">
  2669. <svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" style="color: orangered;fill: orangered;">
  2670. <path d="M775.84 392.768l-155.2-172.352L160.768 643.264l-38.368 187.936 190.56-12.832zM929.952 229.952l-131.2-150.944-0.288-0.32a16 16 0 0 0-22.592-0.96l-131.168 120.576 155.168 172.352 128.832-118.464a15.936 15.936 0 0 0 1.248-22.24zM96 896h832v64H96z">
  2671. </path>
  2672. </svg>
  2673. </button>
  2674. </div>
  2675. <div class="moreConfig">
  2676. <div title="${i18n('forceStateIframe')}">
  2677. <input name="forceState" id="forceStateIframe" type="radio">
  2678. <label for="forceStateIframe">Iframe</label>
  2679. </div>
  2680. <div title="${i18n('forceStateDynamic')}">
  2681. <input name="forceState" id="forceStateDynamic" type="radio">
  2682. <label for="forceStateDynamic">Dynamic</label>
  2683. </div>
  2684. <div title="${i18n('forceStateDisable')}">
  2685. <input name="forceState" id="forceStateDisable" type="radio">
  2686. <label for="forceStateDisable">Disable</label>
  2687. </div>
  2688. </div>
  2689. <button id="nextSwitch" class="command" title="${i18n("nextSwitch")}" type="button">${i18n("nextSwitch")}</button>
  2690. <button id="loadNow" class="command" title="${i18n("loadNow")}" type="button">${i18n("loadNow")}</button>
  2691. `);
  2692. let forceStateIframe = frame.querySelector("#forceStateIframe");//forceState 1 禁用 2 强嵌 3 动态
  2693. let forceStateDynamic = frame.querySelector("#forceStateDynamic");
  2694. let forceStateDisable = frame.querySelector("#forceStateDisable");
  2695. let clickRadio = e => {
  2696. let radio = e.currentTarget.querySelector('input');
  2697. if (radio.checked) {
  2698. forceState = "";
  2699. } else {
  2700. switch (radio.id) {
  2701. case "forceStateIframe":
  2702. forceState = 2;
  2703. break;
  2704. case "forceStateDynamic":
  2705. forceState = 3;
  2706. break;
  2707. case "forceStateDisable":
  2708. forceState = 1;
  2709. break;
  2710. default:
  2711. return;
  2712. }
  2713. }
  2714. storage.setItem("forceState_"+location.host, forceState);
  2715. self.close();
  2716. location.reload();
  2717. };
  2718. forceStateIframe.parentNode.addEventListener("mousedown", clickRadio);
  2719. forceStateDynamic.parentNode.addEventListener("mousedown", clickRadio);
  2720. forceStateDisable.parentNode.addEventListener("mousedown", clickRadio);
  2721. if (forceState == 1) forceStateDisable.checked = true;
  2722. else if (forceState == 2) forceStateIframe.checked = true;
  2723. else if (forceState == 3) forceStateDynamic.checked = true;
  2724. let closeBtn = frame.querySelector(".closePicker");
  2725. let homeBtn = frame.querySelector(".logoToHome");
  2726. let title = frame.querySelector(".title");
  2727. let allpath = frame.querySelector(".allpath");
  2728. let selectorInput = frame.querySelector(".selector");
  2729. let xpath = frame.querySelector("#checkbox_id");
  2730. let checkBtn = frame.querySelector("#check");
  2731. let editBtn = frame.querySelector("#edit");
  2732. let nextSwitch = frame.querySelector("#nextSwitch");
  2733. let loadNow = frame.querySelector("#loadNow");
  2734. nextSwitch.addEventListener("click", e => {
  2735. self.close();
  2736. NextSwitch.getInstance().start();
  2737. }, true);
  2738. loadNow.addEventListener("click", e => {
  2739. self.close();
  2740. let loadNum=window.prompt(i18n("loadConfirm"), "1");
  2741. if(loadNum==="" || loadNum===null)return;
  2742. autoLoadNum=Math.abs(parseInt(loadNum));
  2743. nextPage();
  2744. }, true);
  2745. closeBtn.addEventListener("click", e => {
  2746. self.close();
  2747. }, true);
  2748. homeBtn.addEventListener("click", e => {
  2749. _GM_openInTab(configPage[0], {active: true});
  2750. }, true);
  2751. let moving = false;
  2752. let moveHanlder = e => {
  2753. frame.style.left = e.clientX - 200 + "px";
  2754. frame.style.top = e.clientY - 15 + "px";
  2755. e.stopPropagation();
  2756. e.preventDefault();
  2757. };
  2758. let upHanlder = e => {
  2759. moving = false;
  2760. document.removeEventListener("mousemove", moveHanlder, true);
  2761. title.removeEventListener("mouseup", upHanlder, true);
  2762. e.stopPropagation();
  2763. e.preventDefault();
  2764. };
  2765. title.addEventListener("mousedown", e => {
  2766. moving = true;
  2767. document.addEventListener("mousemove", moveHanlder, true);
  2768. title.addEventListener("mouseup", upHanlder, true);
  2769. });
  2770. frame.addEventListener("mouseenter", e => {
  2771. if (moving) return;
  2772. if (self.mainSignDiv.parentNode) self.mainSignDiv.parentNode.removeChild(self.mainSignDiv);
  2773. self.checkInputSelector();
  2774. });
  2775. frame.addEventListener("mouseleave", e => {
  2776. if (moving) return;
  2777. document.body.appendChild(self.mainSignDiv);
  2778. self.clearSigns();
  2779. });
  2780. checkBtn.addEventListener("click", e => {
  2781. self.checkInputSelector();
  2782. if (this.selectorInput.value) _GM_setClipboard(this.selectorInput.value);
  2783. });
  2784. xpath.addEventListener("click", e => {
  2785. if (!selectorInput.value) {
  2786. self.setSelectorDiv("");
  2787. return;
  2788. }
  2789. let element = getElement(selectorInput.value, document);
  2790. let selector = self.getSelectorFromEle(element);
  2791. self.setSelectorDiv(selector);
  2792. selectorInput.value = selector;
  2793. });
  2794. editBtn.addEventListener("click", e => {
  2795. let editTemp;
  2796. if (ruleParser.curSiteRule.url && !ruleParser.curSiteRule.singleUrl) {
  2797. editTemp = ruleParser.curSiteRule;
  2798. } else {
  2799. editTemp = {
  2800. name: document.title,
  2801. url: "^" + location.origin.replace(/^https?/, "https?").replace(/\./g,"\\.") + "/"
  2802. };
  2803. }
  2804. if (selectorInput.value) {
  2805. editTemp.pageElement = selectorInput.value;
  2806. }
  2807. delete editTemp.from;
  2808. delete editTemp.type;
  2809. delete editTemp.updatedAt;
  2810. rulesData.editTemp = editTemp;
  2811. storage.setItem("rulesData", rulesData);
  2812. _GM_openInTab(configPage[0], {active: true});
  2813. });
  2814. this.frame = frame;
  2815. this.xpath = xpath;
  2816. this.allpath = allpath;
  2817. this.selectorInput = selectorInput;
  2818. this.nextSwitch = nextSwitch;
  2819. this.loadNow = loadNow;
  2820. this.moveHandler = e => {
  2821. if (e.target === document) return;
  2822. self.adjustSignDiv(self.mainSignDiv, self.getTarget(e.target));
  2823. };
  2824. this.clickHandler = e => {
  2825. if (self.inPicker) {
  2826. e.stopPropagation();
  2827. e.preventDefault();
  2828. }
  2829. let target = self.getTarget(e.target);
  2830. let selector = self.getSelectorFromEle(target);
  2831. self.setSelectorDiv(selector);
  2832. selectorInput.value = selector;
  2833. };
  2834. }
  2835.  
  2836. getTarget(ele) {
  2837. while (ele.parentNode && (ele.scrollWidth === 0 || ele.scrollHeight === 0)) {
  2838. ele = ele.parentNode;
  2839. }
  2840. return ele;
  2841. }
  2842.  
  2843. close() {
  2844. this.clearSigns();
  2845. if (this.frame.parentNode) this.frame.parentNode.removeChild(this.frame);
  2846. if (this.mainSignDiv.parentNode) this.mainSignDiv.parentNode.removeChild(this.mainSignDiv);
  2847. document.body.classList.remove("pagetual-picker");
  2848. document.body.removeEventListener("mousemove", this.moveHandler, true);
  2849. document.body.removeEventListener("click", this.clickHandler, true);
  2850. this.inPicker = false;
  2851. }
  2852.  
  2853. setImportant(ele, prop, value) {
  2854. ele.style.setProperty(prop, value, "important");
  2855. }
  2856.  
  2857. createSignDiv() {
  2858. let signDiv = document.createElement("div");
  2859. this.setImportant(signDiv, "position", "absolute");
  2860. this.setImportant(signDiv, "pointer-events", "none");
  2861. this.setImportant(signDiv, "z-index", "2147483647");
  2862. this.setImportant(signDiv, "background", "rgba(120, 170, 210, 0.6)");
  2863. this.setImportant(signDiv, "transition", "all 0.15s ease-out");
  2864. this.setImportant(signDiv, "box-shadow", "rgb(0 0 0) 0px 0px 3px 0px");
  2865. return signDiv;
  2866. }
  2867.  
  2868. adjustSignDiv(div, target) {
  2869. let rect = target.getBoundingClientRect();
  2870. this.setImportant(div, "width", rect.width + "px");
  2871. this.setImportant(div, "height", rect.height + "px");
  2872. this.setImportant(div, "left", rect.left + window.scrollX + "px");
  2873. this.setImportant(div, "top", rect.top + window.scrollY + "px");
  2874. }
  2875.  
  2876. getSelectorFromEle(ele) {
  2877. return this.xpath.checked ? createXPathFromElement(ele) : geneSelector(ele, true);
  2878. }
  2879.  
  2880. setSelectorDiv(selector) {
  2881. let self = this;
  2882. this.allpath.innerHTML = createHTML("");
  2883. if (!selector) return;
  2884. if (this.xpath.checked) {
  2885. let span = document.createElement("span");
  2886. span.innerText = selector;
  2887. span.addEventListener("click", e => {
  2888. self.selectorInput.value = selector;
  2889. self.checkInputSelector();
  2890. }, true);
  2891. this.allpath.appendChild(span);
  2892. } else {
  2893. selector.split(">").forEach((item, index) => self.geneSelectorItem(item, index));
  2894. }
  2895. }
  2896.  
  2897. geneSelectorItem(item, index) {
  2898. let self = this;
  2899. item = item.trim();
  2900. if (!item) return;
  2901. if (index !== 0) {
  2902. let span = document.createElement("span");
  2903. span.innerText = " > ";
  2904. this.allpath.appendChild(span);
  2905. }
  2906. let span = document.createElement("span");
  2907. span.className = "path";
  2908. span.innerText = item;
  2909. span.addEventListener("click", e => {
  2910. let selector = "";
  2911. let target = e.target;
  2912. while (target) {
  2913. selector = target.innerText + selector;
  2914. target = target.previousElementSibling;
  2915. }
  2916. self.selectorInput.value = selector;
  2917. self.checkInputSelector();
  2918. }, true);
  2919. this.allpath.appendChild(span);
  2920. }
  2921.  
  2922. checkInputSelector() {
  2923. let self = this;
  2924. this.clearSigns();
  2925. if (!this.selectorInput.value) return;
  2926. let eles = getAllElements(this.selectorInput.value, document);
  2927. if (eles && eles.length > 0) {
  2928. eles.forEach(ele => {
  2929. let sign = self.createSignDiv();
  2930. document.body.appendChild(sign);
  2931. self.adjustSignDiv(sign, ele);
  2932. self.signList.push(sign);
  2933. });
  2934. }
  2935. }
  2936.  
  2937. clearSigns() {
  2938. this.signList.forEach(sign => {
  2939. if (sign.parentNode) sign.parentNode.removeChild(sign);
  2940. });
  2941. this.signList = [];
  2942. }
  2943.  
  2944. start() {
  2945. if (this.inPicker) return;
  2946. this.inPicker = true;
  2947. document.documentElement.appendChild(this.frame);
  2948. document.body.appendChild(this.mainSignDiv);
  2949. document.body.classList.add("pagetual-picker");
  2950.  
  2951. document.body.addEventListener("mousemove", this.moveHandler, true);
  2952. document.body.addEventListener("click", this.clickHandler, true);
  2953. this.xpath.checked = isXPath(ruleParser.curSiteRule.pageElement);
  2954.  
  2955. this.loadNow.style.display = ruleParser.nextLinkHref ? "block" : "none";
  2956. if (ruleParser.curSiteRule.nextLink && Array && Array.isArray && Array.isArray(ruleParser.curSiteRule.nextLink)) {
  2957. this.nextSwitch.style.display = "block";
  2958. } else {
  2959. this.nextSwitch.style.display = "none";
  2960. }
  2961.  
  2962. let pageElementSel=ruleParser.curSiteRule.pageElement || "";
  2963. if(Array && Array.isArray && Array.isArray(pageElementSel)){
  2964. pageElementSel=pageElementSel[nextIndex<pageElementSel.length?nextIndex:0];
  2965. }
  2966. this.setSelectorDiv(pageElementSel);
  2967. }
  2968. }
  2969.  
  2970. function initConfig(){
  2971. initView();
  2972. try{
  2973. if(_unsafeWindow.initedPagetual){
  2974. if(ruleImportUrlReg.test(location.href)){
  2975. showTips(i18n('duplicate'));
  2976. }
  2977. return true;
  2978. }
  2979. _unsafeWindow.initedPagetual=true;
  2980. }catch(e){}
  2981. _GM_registerMenuCommand(i18n(forceState==1?"enable":"disableSite"), ()=>{
  2982. forceState=(forceState==1?0:1);
  2983. storage.setItem("forceState_"+location.host, forceState);
  2984. showTips(i18n(forceState==1?"disableSiteTips":"enableSiteTips"));
  2985. if(!ruleParser.curSiteRule.url) location.reload();
  2986. });
  2987. _GM_registerMenuCommand(i18n("update"), ()=>{
  2988. updateRules(()=>{
  2989. showTips(i18n("updateSucc"));
  2990. location.reload();
  2991. },(rule,err)=>{
  2992. showTips("Update "+rule.url+" rules fail!");
  2993. });
  2994. showTips(i18n("beginUpdate"));
  2995. });
  2996. if(guidePage.test(location.href)){
  2997. function createEdit(){
  2998. var options = {
  2999. mode: 'code',
  3000. modes: ['code', 'tree'],
  3001. templates: [
  3002. {
  3003. text: 'New site',
  3004. title: 'Insert a new site',
  3005. className: 'jsoneditor-type-object',
  3006. field: 'SiteTemplate',
  3007. value: {
  3008. 'name': 'Site name',
  3009. 'url': 'Site url'
  3010. }
  3011. }
  3012. ],
  3013. schema: {
  3014. "title": "Sites data",
  3015. "description": "Object containing site config",
  3016. "type": "array",
  3017. "items": {
  3018. "type": 'object',
  3019. "properties": {
  3020. "name": {
  3021. "title": "Site Name",
  3022. "description": "The site's name.",
  3023. "examples": [
  3024. "Google"
  3025. ],
  3026. "type": "string"
  3027. },
  3028. "url": {
  3029. "title": "Site Url",
  3030. "description": "The Regexp of site's url.",
  3031. "examples": [
  3032. "^https:\/\/yande\\.re\/"
  3033. ],
  3034. "type": "string"
  3035. }
  3036. },
  3037. "required": ["name", "url"]
  3038. }
  3039. }
  3040. };
  3041. var container = document.getElementById("jsoneditor");
  3042. container.style.height='800px';
  3043. var editor = new JSONEditor(container, options);
  3044. editor.set(ruleParser.customRules);
  3045. document.querySelector("#saveBtn").onclick=e=>{
  3046. try{
  3047. storage.setItem("hpRules", []);
  3048. storage.setItem("smartRules", []);
  3049. let customRules=editor.get();
  3050. if(!customRules){
  3051. storage.setItem("customRules", "");
  3052. }else{
  3053. if(Array && Array.isArray && !Array.isArray(customRules)){
  3054. showTips("Rules must be a Array!");
  3055. return;
  3056. }
  3057. debug(customRules);
  3058. storage.setItem("customRules", customRules);
  3059. }
  3060. }catch(e){
  3061. debug(e);
  3062. showTips("JSON error, check again!");
  3063. return;
  3064. }
  3065. showTips("Edit successfully");
  3066. };
  3067. }
  3068. if(JSONEditor){
  3069. createEdit();
  3070. }else{
  3071. window.onload = e => {
  3072. createEdit();
  3073. }
  3074. }
  3075. return true;
  3076. }
  3077. if(location.href.indexOf("PagetualGuide")!=-1) return true;
  3078.  
  3079. var configCon,insertPos;
  3080. var noRules=!rulesData.urls || rulesData.urls.length===0;
  3081.  
  3082. let inConfig = false;
  3083. for (let i = 0; i < configPage.length; i++) {
  3084. if (configPage[i] == location.href) {
  3085. inConfig = true;
  3086. break;
  3087. }
  3088. }
  3089. if(ruleImportUrlReg.test(location.href) || inConfig){
  3090. let importing = false;
  3091. if(noRules){
  3092. setTimeout(() => {
  3093. if (!importing) showTips(i18n("firstAlert"));
  3094. }, 3000);
  3095. setTimeout(() => {
  3096. if (!importing) showTips(i18n("firstAlert"));
  3097. }, 6000);
  3098. showTips(i18n("firstAlert"));
  3099. }
  3100. let createImportBtn = () => {
  3101. let importBtn = document.createElement("button");
  3102. importBtn.innerText = i18n("import");
  3103. importBtn.style.marginTop = "100px";
  3104. importBtn.style.float = "right";
  3105. importBtn.style.position = "relative";
  3106. importBtn.style.display = "block";
  3107. importBtn.style.fontSize = "20px";
  3108. importBtn.addEventListener("click", e => {
  3109. let parentNode = importBtn.parentNode;
  3110. if (!parentNode) return;
  3111. parentNode.removeChild(importBtn);
  3112. try {
  3113. let rules=parentNode.innerText.trim();
  3114. let isContent=/['"]name['"]/i.test(rules);
  3115. if(isContent){
  3116. let ruleList=JSON.parse(`[${rules}]`);
  3117. for(let i in ruleList){
  3118. let hasRule = false;
  3119. let r = ruleList[i];
  3120. for(let j in ruleParser.customRules){
  3121. if(ruleParser.customRules[j].name == r.name){
  3122. ruleParser.customRules[j] = r;
  3123. hasRule = true;
  3124. break;
  3125. }
  3126. }
  3127. if(!hasRule)ruleParser.customRules.push(r);
  3128. }
  3129. storage.setItem("customRules", ruleParser.customRules);
  3130. storage.setItem("hpRules", []);
  3131. storage.setItem("smartRules", []);
  3132. showTips(i18n("importSucc"));
  3133. }else{
  3134. rules=rules.split("\n");
  3135. let diff=false;
  3136. for(let c=0;c<rules.length;c++){
  3137. let urlArr=rules[c].split("|"),url,type=1;
  3138. if(urlArr.length==1){
  3139. url=urlArr[0].trim();
  3140. if(!/^http/.test(url)){
  3141. showTips("Wrong url, check again!");
  3142. return;
  3143. }
  3144. }else if(urlArr.length==2){
  3145. type=urlArr[0].trim();
  3146. url=urlArr[1].trim();
  3147. if(!/^http/.test(url)){
  3148. showTips("Wrong url, check again!");
  3149. return;
  3150. }
  3151. }else{
  3152. break;
  3153. }
  3154. let maxId=0,hasUrl=false;
  3155. if(!rulesData.urls){
  3156. rulesData.urls=[];
  3157. maxId=1;
  3158. }else{
  3159. rulesData.urls.forEach(u=>{
  3160. if(maxId<u.id){
  3161. maxId=u.id;
  3162. }
  3163. if(u.url==url){
  3164. hasUrl=true;
  3165. }
  3166. });
  3167. if(hasUrl)break;
  3168. }
  3169. diff=true;
  3170. if(!rulesData.sort)rulesData.sort=[1];
  3171. rulesData.urls.push({id:maxId+1,url:url,type:type});
  3172. rulesData.sort.unshift(maxId+1);
  3173. }
  3174. if(!diff){
  3175. showTips("Already exists!");
  3176. return;
  3177. }
  3178. storage.setItem("rulesData", rulesData);
  3179.  
  3180. if(rulesData.urls)ruleUrls=ruleUrls.concat(rulesData.urls);
  3181. if(rulesData.sort){
  3182. let urls=[];
  3183. rulesData.sort.forEach(id=>{
  3184. for(let s=0;s<ruleUrls.length;s++){
  3185. if(id==ruleUrls[s].id){
  3186. urls.push(ruleUrls[s]);
  3187. break;
  3188. }
  3189. }
  3190. });
  3191. ruleUrls=urls;
  3192. }
  3193. updateRules(()=>{
  3194. showTips(i18n("updateSucc"));
  3195. location.reload();
  3196. },(rule,err)=>{
  3197. showTips("Update "+rule.url+" rules fail!");
  3198. });
  3199. importing = true;
  3200. showTips(i18n("beginUpdate"));
  3201. }
  3202. } catch (e) {
  3203. _GM_notification(e.toString());
  3204. }
  3205. });
  3206. return importBtn;
  3207. };
  3208. [].forEach.call(document.querySelectorAll('pre[name=pagetual],pre[name=user-content-pagetual]'), pre => {
  3209. let importBtn = createImportBtn();
  3210. let clientHeight = 35 - pre.clientHeight;
  3211. if (clientHeight > -20) clientHeight = -20;
  3212. importBtn.style.marginTop = `${clientHeight}px`;
  3213. pre.appendChild(importBtn);
  3214. });
  3215. document.addEventListener("mouseover", e => {
  3216. if (e.target.tagName === "PRE") {
  3217. let nameAttr=e.target.getAttribute("name");
  3218. if(nameAttr=="pagetual" || nameAttr=="user-content-pagetual"){
  3219. if (e.target.querySelector('button')) return;
  3220. let importBtn = createImportBtn();
  3221. let clientHeight = 35 - e.target.clientHeight;
  3222. if (clientHeight > -20) clientHeight = -20;
  3223. importBtn.style.marginTop = `${clientHeight}px`;
  3224. e.target.appendChild(importBtn);
  3225. }
  3226. }
  3227. });
  3228.  
  3229. if(inConfig){
  3230. _GM_addStyle(`
  3231. p>span:nth-child(1),p>span:nth-child(2),p>span:nth-child(3){
  3232. cursor: pointer;
  3233. user-select: none;
  3234. }
  3235. p>span:nth-child(1):hover,p>span:nth-child(2):hover,p>span:nth-child(3):hover{
  3236. color:red;
  3237. }
  3238. .updateDate{
  3239. cursor: pointer;
  3240. user-select: none;
  3241. }
  3242. .updateDate:hover{
  3243. color:red;
  3244. }
  3245. input[type=number]::-webkit-inner-spin-button,
  3246. input[type=number]::-webkit-outer-spin-button {
  3247. -webkit-appearance: none;
  3248. margin: 0;
  3249. }
  3250. input[type=number] {
  3251. -moz-appearance:textfield;
  3252. }
  3253. `);
  3254. document.querySelector("[name='user-content-click2import'],[name='click2import']").innerText=i18n("click2ImportRule")
  3255. configCon=document.querySelector(".markdown-body");
  3256. insertPos=configCon.querySelector("hr");
  3257.  
  3258. if(!noRules){
  3259. document.querySelector("pre[name='user-content-pagetual'],pre[name='pagetual']").style.display="none";
  3260. document.querySelector("p[name='user-content-click2import'],p[name='click2import']").style.display="none";
  3261. }
  3262. }else return true;
  3263. }else return false;
  3264. class Rulebar {
  3265. init(ruleUrl){
  3266. this.ruleUrl=ruleUrl;
  3267. this.item=document.createElement("p");
  3268. this.item.dataset.id=this.ruleUrl.id;
  3269. let url=document.createElement("span");
  3270. url.innerHTML=ruleUrl.url;
  3271. let up=document.createElement("span");
  3272. up.innerHTML="↑ ";
  3273. up.title=i18n("sortTitle");
  3274. let down=document.createElement("span");
  3275. down.innerHTML="↓ ";
  3276. down.title=i18n("sortTitle");
  3277. let del=document.createElement("span");
  3278. del.innerHTML="× ";
  3279. up.onclick=e=>{
  3280. this.moveUp();
  3281. };
  3282. down.onclick=e=>{
  3283. this.moveDown();
  3284. };
  3285. del.onclick=e=>{
  3286. this.del();
  3287. };
  3288. this.item.appendChild(up);
  3289. this.item.appendChild(down);
  3290. this.item.appendChild(del);
  3291. this.item.appendChild(url);
  3292. configCon.insertBefore(this.item, insertPos);
  3293. }
  3294. saveSort(){
  3295. let sort=[];
  3296. [].forEach.call(this.item.parentNode.querySelectorAll("p[data-id]"), i=>{
  3297. sort.push(i.dataset.id);
  3298. });
  3299. rulesData.sort=sort;
  3300. storage.setItem("rulesData", rulesData);
  3301. }
  3302. moveUp(){
  3303. let preE=this.item.previousElementSibling;
  3304. if(preE.tagName=="P" && preE.children.length>1){
  3305. this.item.parentNode.insertBefore(this.item,preE);
  3306. this.saveSort();
  3307. }
  3308. }
  3309. moveDown(){
  3310. let nextE=this.item.nextElementSibling;
  3311. if(nextE.tagName=="P" && nextE.children.length>1){
  3312. this.item.parentNode.insertBefore(nextE,this.item);
  3313. this.saveSort();
  3314. }
  3315. }
  3316. del(){
  3317. if(this.ruleUrl.id<2){
  3318. showTips(i18n("cantDel"));
  3319. }else if(window.confirm(i18n("confirmDel"))){
  3320. for(let u=0;u<rulesData.urls.length;u++){
  3321. if(this.ruleUrl.id==rulesData.urls[u].id){
  3322. rulesData.urls.splice(u,1);
  3323. break;
  3324. }
  3325. }
  3326. for(let u=0;u<ruleUrls.length;u++){
  3327. if(this.ruleUrl.id==ruleUrls[u].id){
  3328. ruleUrls.splice(u,1);
  3329. break;
  3330. }
  3331. }
  3332. for(let u=0;u<rulesData.sort.length;u++){
  3333. if(this.ruleUrl.id==rulesData.sort[u]){
  3334. rulesData.sort.splice(u,1);
  3335. break;
  3336. }
  3337. }
  3338. storage.setItem("rulesData", rulesData);
  3339. ruleParser.rules=ruleParser.rules.filter(item=>{return item.from!=this.ruleUrl.id});
  3340. storage.setItem("rules", ruleParser.rules);
  3341. this.item.parentNode.removeChild(this.item);
  3342. //location.reload();
  3343. }
  3344. }
  3345. }
  3346. let updateP=document.createElement("p"),i=0;
  3347. let now=new Date().getTime(),inUpdate=false;
  3348.  
  3349.  
  3350. let pastDate=(new Date(updateDate)).toString(),passStr;
  3351. let passTime=(now-updateDate)/1000;
  3352. if(isNaN(passTime)){
  3353. passStr=i18n("firstUpdate");
  3354. }else if(passTime<60){
  3355. passStr=i18n("passSec", parseInt(passTime))+" 👆 "+i18n("click2update");
  3356. }else if(passTime<60*60){
  3357. passStr=i18n("passMin", parseInt(passTime/60))+" 👆 "+i18n("click2update");
  3358. }else if(passTime<60*60*24){
  3359. passStr=i18n("passHour", parseInt(passTime/3600))+" 👆 "+i18n("click2update");
  3360. }else{
  3361. passStr=i18n("passDay", parseInt(passTime/86400))+" 👆 "+i18n("click2update");
  3362. }
  3363.  
  3364.  
  3365. updateP.className="updateDate";
  3366. updateP.innerHTML=passStr;
  3367. updateP.title=i18n("update")+" - "+pastDate;
  3368. updateP.onclick=e=>{
  3369. updateRules(()=>{
  3370. showTips(i18n("updateSucc"));
  3371. updateP.innerHTML=i18n("passSec", 0);
  3372. updateP.title=i18n("update");
  3373. },(rule,err)=>{
  3374. showTips("Update "+rule.url+" rules fail!");
  3375. });
  3376. showTips(i18n("beginUpdate"));
  3377. };
  3378. configCon.insertBefore(updateP, insertPos);
  3379. if(ruleUrls){
  3380. ruleUrls.forEach(ruleUrl=>{
  3381. var rulebar=new Rulebar();
  3382. rulebar.init(ruleUrl);
  3383. });
  3384. }
  3385. let customUrlsTitle=document.createElement("h2");
  3386. customUrlsTitle.innerHTML=i18n("customUrls");
  3387. configCon.insertBefore(customUrlsTitle, insertPos);
  3388. let customUrlsInput=document.createElement("textarea");
  3389. customUrlsInput.style.width="100%";
  3390. customUrlsInput.placeholder="http://wedata.net/databases/AutoPagerize/items_all.json";
  3391. customUrlsInput.spellcheck=false;
  3392. configCon.insertBefore(customUrlsInput, insertPos);
  3393.  
  3394. let btns=document.createElement("div");
  3395. btns.style.display="flex";
  3396. configCon.insertBefore(btns, insertPos);
  3397. let upBtnImg=document.createElement("div");
  3398. upBtnImg.style.width="50%";
  3399. let upBtnImgTitle=document.createElement("h2");
  3400. upBtnImgTitle.style.whiteSpace="nowrap";
  3401. upBtnImgTitle.style.overflow="auto";
  3402. upBtnImgTitle.innerHTML=i18n("upBtnImg");
  3403. upBtnImg.appendChild(upBtnImgTitle);
  3404. let upBtnImgInput=document.createElement("input");
  3405. upBtnImgInput.style.width="100%";
  3406. upBtnImgInput.placeholder="data:image/png;base64,UpBtn";
  3407. upBtnImgInput.value=rulesData.upBtnImg||'';
  3408. upBtnImgInput.spellcheck=false;
  3409. upBtnImg.appendChild(upBtnImgInput);
  3410. btns.appendChild(upBtnImg);
  3411.  
  3412. let downBtnImg=document.createElement("div");
  3413. downBtnImg.style.width="50%";
  3414. let downBtnImgTitle=document.createElement("h2");
  3415. downBtnImgTitle.style.whiteSpace="nowrap";
  3416. downBtnImgTitle.style.overflow="auto";
  3417. downBtnImgTitle.innerHTML=i18n("downBtnImg");
  3418. downBtnImg.appendChild(downBtnImgTitle);
  3419. let downBtnImgInput=document.createElement("input");
  3420. downBtnImgInput.style.width="100%";
  3421. downBtnImgInput.placeholder="data:image/png;base64,DownBtn";
  3422. downBtnImgInput.value=rulesData.downBtnImg||'';
  3423. downBtnImgInput.spellcheck=false;
  3424. downBtnImg.appendChild(downBtnImgInput);
  3425. btns.appendChild(downBtnImg);
  3426.  
  3427. let otherBtns=document.createElement("div");
  3428. otherBtns.style.display="flex";
  3429. configCon.insertBefore(otherBtns, insertPos);
  3430. let loadingText=document.createElement("div");
  3431. loadingText.style.width="100%";
  3432. let loadingTextTitle=document.createElement("h2");
  3433. loadingTextTitle.style.whiteSpace="nowrap";
  3434. loadingTextTitle.style.overflow="auto";
  3435. loadingTextTitle.innerHTML=i18n("loadingTextTitle");
  3436. loadingText.appendChild(loadingTextTitle);
  3437. let loadingTextInput=document.createElement("input");
  3438. loadingTextInput.value=rulesData.loadingText||'';
  3439. loadingTextInput.placeholder=i18n("loadingText");
  3440. loadingTextInput.style.width="100%";
  3441. loadingTextInput.style.margin="0";
  3442. loadingTextInput.spellcheck=false;
  3443. loadingText.appendChild(loadingTextInput);
  3444. otherBtns.appendChild(loadingText);
  3445.  
  3446. let opacity=document.createElement("div");
  3447. let opacityTitle=document.createElement("h2");
  3448. opacityTitle.style.whiteSpace="nowrap";
  3449. opacityTitle.style.overflow="visible";
  3450. opacityTitle.innerHTML=i18n("opacity");
  3451. opacity.appendChild(opacityTitle);
  3452. let opacityInput=document.createElement("input");
  3453. opacityInput.value=rulesData.opacity*100;
  3454. opacityInput.type="number";
  3455. opacityInput.style.width="110px";
  3456. opacityInput.style.margin="0";
  3457. opacityInput.placeholder=i18n("opacityPlaceholder");
  3458. opacityInput.spellcheck=false;
  3459. opacity.appendChild(opacityInput);
  3460. otherBtns.appendChild(opacity);
  3461.  
  3462. let pageElementCss=document.createElement("div");
  3463. pageElementCss.style.marginBottom="30px";
  3464. let pageElementCssTitle=document.createElement("h2");
  3465. pageElementCssTitle.innerHTML=i18n("pageElementCss");
  3466. pageElementCss.appendChild(pageElementCssTitle);
  3467. let pageElementCssInput=document.createElement("input");
  3468. pageElementCssInput.value=rulesData.pageElementCss||'';
  3469. pageElementCssInput.style.width="100%";
  3470. pageElementCssInput.style.margin="0";
  3471. pageElementCssInput.placeholder="font-size: xx-large;";
  3472. pageElementCssInput.spellcheck=false;
  3473. pageElementCss.appendChild(pageElementCssInput);
  3474. configCon.insertBefore(pageElementCss, insertPos);
  3475.  
  3476. let customCss=document.createElement("div");
  3477. customCss.style.marginBottom="50px";
  3478. let customCssTitle=document.createElement("h2");
  3479. customCssTitle.innerHTML=i18n("customCss");
  3480. customCss.appendChild(customCssTitle);
  3481. let customCssInput=document.createElement("textarea");
  3482. customCssInput.value=rulesData.customCss||'';
  3483. customCssInput.style.width="100%";
  3484. customCssInput.style.margin="0";
  3485. customCssInput.placeholder=".pagetual{\n}";
  3486. customCssInput.spellcheck=false;
  3487. customCss.appendChild(customCssInput);
  3488. configCon.insertBefore(customCss, insertPos);
  3489.  
  3490. let configTable=document.createElement("table");
  3491. configTable.style.width="100%";
  3492. let configTbody=document.createElement("tbody");
  3493. configTbody.style.width="100%";
  3494. configTbody.style.display="inline-table";
  3495. configTable.appendChild(configTbody);
  3496. configCon.insertBefore(configTable, insertPos);
  3497. function createCheckbox(innerText, val, tag, parentCheck, otherType) {
  3498. if (typeof val == 'undefined') val = "";
  3499. let title=document.createElement(tag || "h3");
  3500. title.innerHTML = innerText;
  3501. title.style.overflowWrap = "normal";
  3502. let input = document.createElement("input");
  3503. if (otherType === 'key') {
  3504. input.type = 'text';
  3505. input.setAttribute('readOnly', 'readonly');
  3506. input.addEventListener("keydown", e => {
  3507. if (e.key === 'Escape' || e.key === 'Backspace') input.value = '';
  3508. else input.value = e.key;
  3509. e.stopPropagation();
  3510. e.preventDefault();
  3511. });
  3512. } else {
  3513. input.type = otherType || "checkbox";
  3514. }
  3515. input.style.width = "30px";
  3516. input.style.height = "20px";
  3517. input.style.float = "left";
  3518. input.style.margin = "5px";
  3519. input.value = val;
  3520. input.checked = val;
  3521. let td = document.createElement("td");
  3522. td.appendChild(input);
  3523. if (parentCheck) {
  3524. title.style.margin = "0";
  3525. td.appendChild(title);
  3526. let parent = parentCheck.parentNode.nextElementSibling;
  3527. let tr = parent.querySelector("tr");
  3528. if (!tr) {
  3529. tr = document.createElement("tr");
  3530. parent.appendChild(tr);
  3531. }
  3532. tr.appendChild(td);
  3533. if (!parentCheck.checked) {
  3534. td.style.display = "none";
  3535. }
  3536. parentCheck.addEventListener("click", e => {
  3537. td.style.display = parentCheck.checked ? "" : "none";
  3538. });
  3539. } else {
  3540. let tr = document.createElement("tr");
  3541. tr.appendChild(td);
  3542. td = document.createElement("td");
  3543. td.appendChild(title);
  3544. tr.appendChild(td);
  3545. configTable.children[0].appendChild(tr);
  3546. }
  3547. return input;
  3548. }
  3549.  
  3550. let enableWhiteListInput=createCheckbox(i18n("autoRun"), rulesData.enableWhiteList!=true);
  3551. let enableDebugInput=createCheckbox(i18n("enableDebug"), rulesData.enableDebug!=false);
  3552. let enableHistoryInput=createCheckbox(i18n("enableHistory"), rulesData.enableHistory===true);
  3553. let enableHistoryAfterInsertInput=createCheckbox(i18n("enableHistoryAfterInsert"), rulesData.enableHistoryAfterInsert===true);
  3554. let openInNewTabInput=createCheckbox(i18n("openInNewTab"), rulesData.openInNewTab!=false);
  3555. let hideLoadingIconInput=createCheckbox(i18n("hideLoadingIcon"), rulesData.hideLoadingIcon!=false);
  3556. let initRunInput=createCheckbox(i18n("initRun"), rulesData.initRun!=false);
  3557. let autoLoadNumInput=createCheckbox(i18n("autoLoadNum"), rulesData.autoLoadNum, "h4", initRunInput, "number");
  3558. let preloadInput=createCheckbox(i18n("preload"), rulesData.preload!=false);
  3559. let dbClick2StopInput=createCheckbox(i18n("dbClick2Stop"), rulesData.dbClick2Stop);
  3560. let manualModeInput=createCheckbox(i18n("manualMode"), rulesData.manualMode);
  3561. let clickModeInput=createCheckbox(i18n("clickMode"), rulesData.clickMode);
  3562. let pageBarMenuInput=createCheckbox(i18n("pageBarMenu"), rulesData.pageBarMenu);
  3563. let arrowToScrollInput=createCheckbox(i18n("arrowToScroll"), rulesData.arrowToScroll);
  3564.  
  3565. let hideBarInput = createCheckbox(i18n("hideBar"), rulesData.hideBar && !rulesData.hideBarButNoStop, "h4", dbClick2StopInput, 'radio');
  3566. hideBarInput.name = 'hideBar';
  3567. let hideBarButNoStopInput = createCheckbox(i18n("hideBarButNoStop"), rulesData.hideBarButNoStop, "h4", dbClick2StopInput, 'radio');
  3568. hideBarButNoStopInput.name = 'hideBar';
  3569. hideBarInput.addEventListener('mouseup', e => {
  3570. if (hideBarInput.checked) {
  3571. setTimeout(() => {hideBarInput.checked = false}, 0);
  3572. }
  3573. });
  3574. hideBarButNoStopInput.addEventListener('mouseup', e => {
  3575. if (hideBarButNoStopInput.checked) {
  3576. setTimeout(() => {hideBarButNoStopInput.checked = false}, 0);
  3577. }
  3578. });
  3579.  
  3580. let dbClick2StopCtrlInput=createCheckbox(i18n("dbClick2StopCtrl"), rulesData.dbClick2StopCtrl, "h4", dbClick2StopInput);
  3581. let dbClick2StopAltInput=createCheckbox(i18n("dbClick2StopAlt"), rulesData.dbClick2StopAlt, "h4", dbClick2StopInput);
  3582. let dbClick2StopShiftInput=createCheckbox(i18n("dbClick2StopShift"), rulesData.dbClick2StopShift, "h4", dbClick2StopInput);
  3583. let dbClick2StopMetaInput=createCheckbox(i18n("dbClick2StopMeta"), rulesData.dbClick2StopMeta, "h4", dbClick2StopInput);
  3584. let dbClick2StopKeyInput=createCheckbox(i18n("dbClick2StopKey"), rulesData.dbClick2StopKey, "h4", dbClick2StopInput, "key");
  3585.  
  3586. let customRulesTitle=document.createElement("h2");
  3587. customRulesTitle.innerHTML=i18n("customRules");
  3588. configCon.insertBefore(customRulesTitle, insertPos);
  3589. let customRulesInput=document.createElement("textarea");
  3590. customRulesInput.spellcheck=false;
  3591. configCon.insertBefore(customRulesInput, insertPos);
  3592. if(rulesData.editTemp){
  3593. if(!ruleParser.customRules){
  3594. ruleParser.customRules=[];
  3595. }
  3596. for(let i in ruleParser.customRules){
  3597. if(ruleParser.customRules[i].url==rulesData.editTemp.url){
  3598. ruleParser.customRules.splice(i, 1);
  3599. break;
  3600. }
  3601. }
  3602. ruleParser.customRules.unshift(rulesData.editTemp);
  3603. rulesData.editTemp=null;
  3604. storage.setItem("rulesData", rulesData);
  3605. customRulesInput.previousElementSibling.scrollIntoView();
  3606. }
  3607. customRulesInput.style.width="100%";
  3608. customRulesInput.style.height="800px";
  3609. 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]`;
  3610. customRulesInput.value=getFormatJSON(ruleParser.customRules);
  3611. let blacklistInput=document.createElement("textarea");
  3612. blacklistInput.style.width="100%";
  3613. blacklistInput.style.height="500px";
  3614. blacklistInput.style.display="none";
  3615. blacklistInput.spellcheck=false;
  3616. blacklistInput.placeholder="http://*.xxx.com/*/y";
  3617. blacklistInput.value=rulesData.blacklist?rulesData.blacklist.join("\n"):"";
  3618. let blacklistBtn=document.createElement("button");
  3619. blacklistBtn.innerText=i18n("editBlacklist");
  3620. blacklistBtn.style.width="100%";
  3621. blacklistBtn.onclick=e=>{
  3622. blacklistInput.style.display=blacklistInput.style.display=="none"?"":"none";
  3623. };
  3624. configCon.insertBefore(blacklistBtn, insertPos);
  3625. configCon.insertBefore(blacklistInput, insertPos);
  3626. let saveBtn=document.createElement("button");
  3627. saveBtn.innerHTML=i18n("save");
  3628. saveBtn.style.width="100%";
  3629. saveBtn.style.position="fixed";
  3630. saveBtn.style.zIndex="999";
  3631. saveBtn.style.bottom=0;
  3632. saveBtn.style.left=0;
  3633. saveBtn.style.fontSize="x-large";
  3634. configCon.insertBefore(saveBtn, insertPos);
  3635. saveBtn.onclick=e=>{
  3636. try{
  3637. storage.setItem("hpRules", []);
  3638. storage.setItem("smartRules", []);
  3639. if(customRulesInput.value==""){
  3640. storage.setItem("customRules", "");
  3641. }else{
  3642. let customRules=JSON.parse(customRulesInput.value);
  3643. if(Array && Array.isArray && !Array.isArray(customRules)){
  3644. showTips("Rules must be a Array!");
  3645. return;
  3646. }
  3647. debug(customRules);
  3648. storage.setItem("customRules", customRules);
  3649. customRulesInput.value=JSON.stringify(customRules, null, 4);
  3650. }
  3651. }catch(e){
  3652. debug(e);
  3653. showTips("JSON error, check again!");
  3654. return;
  3655. }
  3656. rulesData.opacity = opacityInput.value / 100;
  3657. rulesData.blacklist = blacklistInput.value ? blacklistInput.value.split("\n") : "";
  3658. rulesData.hideBar = hideBarInput.checked;
  3659. rulesData.hideBarButNoStop = hideBarButNoStopInput.checked;
  3660. rulesData.dbClick2Stop = dbClick2StopInput.checked;
  3661. rulesData.enableWhiteList = !enableWhiteListInput.checked;
  3662. rulesData.enableDebug = enableDebugInput.checked;
  3663. rulesData.enableHistory = enableHistoryInput.checked;
  3664. rulesData.enableHistoryAfterInsert = enableHistoryAfterInsertInput.checked;
  3665. rulesData.openInNewTab = openInNewTabInput.checked;
  3666. rulesData.hideLoadingIcon = hideLoadingIconInput.checked;
  3667. rulesData.initRun = initRunInput.checked;
  3668. rulesData.autoLoadNum = autoLoadNumInput.value !== "0" ? autoLoadNumInput.value : '';
  3669. rulesData.preload = preloadInput.checked;
  3670. rulesData.manualMode = manualModeInput.checked;
  3671. rulesData.clickMode = clickModeInput.checked;
  3672. rulesData.pageBarMenu = pageBarMenuInput.checked;
  3673. rulesData.arrowToScroll = arrowToScrollInput.checked;
  3674. rulesData.pageElementCss = pageElementCssInput.value;
  3675. rulesData.customCss = customCssInput.value;
  3676. rulesData.upBtnImg = upBtnImgInput.value;
  3677. rulesData.downBtnImg = downBtnImgInput.value;
  3678. rulesData.loadingText = loadingTextInput.value;
  3679. rulesData.dbClick2StopCtrl = dbClick2StopCtrlInput.checked;
  3680. rulesData.dbClick2StopAlt = dbClick2StopAltInput.checked;
  3681. rulesData.dbClick2StopShift = dbClick2StopShiftInput.checked;
  3682. rulesData.dbClick2StopMeta = dbClick2StopMetaInput.checked;
  3683. rulesData.dbClick2StopKey = dbClick2StopKeyInput.value;
  3684. storage.setItem("rulesData", rulesData);
  3685. let customUrls = customUrlsInput.value.trim();
  3686. if (customUrls) {
  3687. customUrls = customUrls.split(/\n/);
  3688. for (let c = 0; c < customUrls.length; c++) {
  3689. let url;
  3690. if(/^0\s*\|/.test(customUrls[c])){
  3691. url=customUrls[c].replace(/^0\s*\|\s*/, "").trim();
  3692. if(!/^http/.test(url)){
  3693. showTips("Wrong url, check again!");
  3694. return;
  3695. }
  3696. }else{
  3697. url=customUrls[c].trim();
  3698. if(!/^http/.test(url)){
  3699. showTips("Wrong url, check again!");
  3700. return;
  3701. }
  3702. }
  3703. let maxId=1,hasUrl=false;
  3704. if(!rulesData.urls){
  3705. rulesData.urls=[];
  3706. }
  3707. ruleUrls.forEach(u=>{
  3708. if(maxId<u.id){
  3709. maxId=u.id;
  3710. }
  3711. if(u.url==url){
  3712. hasUrl=true;
  3713. }
  3714. });
  3715. if(hasUrl)break;
  3716. if(!rulesData.sort)rulesData.sort=[1];
  3717. rulesData.urls.push({id:maxId+1,url:url});
  3718. rulesData.sort.push(maxId+1);
  3719. storage.setItem("rulesData", rulesData);
  3720. }
  3721. }
  3722. showTips("The settings are saved, refresh to view");
  3723. //location.reload();
  3724. };
  3725. return true;
  3726. }
  3727.  
  3728. var inUpdate=false;
  3729. function updateRules(success,fail){
  3730. if(inUpdate)return;
  3731. inUpdate=true;
  3732. let ruleIndex=ruleUrls.length-1;
  3733. storage.setItem("hpRules", []);
  3734. storage.setItem("smartRules", []);
  3735. function addNextRule(){
  3736. if(ruleIndex<0){
  3737. let now=new Date().getTime();
  3738. storage.setItem("ruleLastUpdate", now);
  3739. storage.setItem("rules", ruleParser.rules);
  3740. inUpdate=false;
  3741. success();
  3742. }else{
  3743. let rule=ruleUrls[ruleIndex--];
  3744. ruleParser.addRuleByUrl(rule.url, rule.id, (json,err)=>{
  3745. if(!json){
  3746. fail(rule,err);
  3747. }
  3748. addNextRule();
  3749. })
  3750. }
  3751. }
  3752. addNextRule();
  3753. }
  3754.  
  3755. function objIsArr(obj) {
  3756. return obj &&
  3757. typeof obj === 'object' &&
  3758. typeof obj.length === 'number' &&
  3759. !(obj.propertyIsEnumerable('length'));
  3760. }
  3761.  
  3762. function isVisible(el, win) {
  3763. if(!el || !el.offsetParent)return false;
  3764. var loopable = true,
  3765. visible = el.tagName && win.getComputedStyle(el).display != 'none' && win.getComputedStyle(el).visibility != 'hidden';
  3766. while(loopable && visible) {
  3767. el = el.parentNode;
  3768.  
  3769. if(el && el.tagName && el.tagName!="BODY") {
  3770. visible = win.getComputedStyle(el).display != 'none' && win.getComputedStyle(el).visibility != 'hidden';
  3771. }else {
  3772. loopable = false;
  3773. }
  3774. }
  3775. return visible;
  3776. }
  3777.  
  3778. function getElementTop(ele) {
  3779. if (!ele) return 0;
  3780. var actualTop = ele.offsetTop;
  3781. var current = ele.offsetParent;
  3782. while (current) {
  3783. actualTop += current.offsetTop;
  3784. current = current.offsetParent;
  3785. }
  3786. return actualTop;
  3787. }
  3788.  
  3789. function getElementBottom(ele) {
  3790. return getElementTop(ele) + ele.offsetHeight;
  3791. }
  3792.  
  3793. function getFormatJSON(obj){
  3794. if(!objIsArr(obj) || obj.length === 0)return "";
  3795. return JSON.stringify(obj, null, 4);
  3796. let ret="[\n";
  3797. let len=obj.length,i=0,isLast;
  3798. obj.forEach(item=>{
  3799. ret+=" {\n";
  3800. let iLen=Object.keys(item).length,j=0;
  3801. for(let key in item){
  3802. isLast=(++j)==iLen;
  3803. let value=item[key];
  3804. if(objIsArr(value)){
  3805. let vstr="[",v=0,vIsLast=false;
  3806. value.forEach(vi=>{
  3807. vIsLast=(++v)==value.length;
  3808. vstr+="\""+vi.replace(/\\/g,"\\\\")+"\""+(vIsLast?"":",");
  3809. });
  3810. vstr+="]";
  3811. ret+=" \""+key+"\":"+vstr+""+(isLast?"":",")+"\n";
  3812. }else{
  3813. if(typeof value=="string"){
  3814. value=value.replace(/\\/g,"\\\\").replace(/"/g,"\\\"");
  3815. value="\""+value+"\"";
  3816. }
  3817. ret+=" \""+key+"\":"+value+""+(isLast?"":",")+"\n";
  3818. }
  3819. }
  3820. isLast=(++i)==len;
  3821. ret+=" }"+(isLast?"":",")+"\n";
  3822. });
  3823. ret+="]";
  3824. return ret;
  3825. }
  3826.  
  3827. function globMatch(first, second) {
  3828. if (first.length == 0 && second.length == 0){
  3829. return true;
  3830. }
  3831.  
  3832. if (first.length > 1 && first[0] == '*' &&
  3833. second.length == 0){
  3834. return false;
  3835. }
  3836.  
  3837. if ((first.length > 1 && first[0] == '?') ||
  3838. (first.length != 0 && second.length != 0 &&
  3839. first[0] == second[0])){
  3840. return globMatch(first.substring(1),
  3841. second.substring(1));
  3842. }
  3843.  
  3844. if (first.length > 0 && first[0] == '*'){
  3845. return globMatch(first.substring(1), second) ||
  3846. globMatch(first, second.substring(1));
  3847. }
  3848.  
  3849. return false;
  3850. }
  3851.  
  3852. function initRules(callback) {
  3853. /*0 wedata格式,1 pagetual格式*/
  3854. ruleUrls=[
  3855. {
  3856. id:1,
  3857. url:'http://wedata.net/databases/AutoPagerize/items_all.json',
  3858. type:0,
  3859. }
  3860. ];var i=0,j=0;
  3861.  
  3862. ruleParser.initSavedRules(()=>{
  3863. storage.getItem("rulesData", data=>{
  3864. if(data){
  3865. rulesData=data;
  3866. if(data.urls)ruleUrls=ruleUrls.concat(data.urls);
  3867. if(data.sort){
  3868. let urls=[];
  3869. data.sort.forEach(id=>{
  3870. for(let s=0;s<ruleUrls.length;s++){
  3871. if(id==ruleUrls[s].id){
  3872. urls.push(ruleUrls[s]);
  3873. break;
  3874. }
  3875. }
  3876. });
  3877. ruleUrls=urls;
  3878. }
  3879. }
  3880. let upBtnImg=rulesData.upBtnImg,downBtnImg=rulesData.downBtnImg;
  3881. if(upBtnImg && downBtnImg){
  3882. downSvgCSS=downSvgCSS.replace("transform: rotate(180deg);","");
  3883. }else if(upBtnImg && !downBtnImg){
  3884. downBtnImg=upBtnImg;
  3885. }else if(downBtnImg && !upBtnImg){
  3886. upBtnImg=downBtnImg;
  3887. }
  3888. if(upBtnImg){
  3889. upSvg=`<img class="pagetual" src="${upBtnImg}"/>`;
  3890. }
  3891. if(downBtnImg){
  3892. downSvg=`<img class="pagetual" src="${downBtnImg}"/>`;
  3893. }
  3894. setLoadingDiv(rulesData.loadingText || i18n("loadingText"));
  3895. if(typeof(rulesData.opacity)=="undefined"){
  3896. rulesData.opacity=0.3;
  3897. }
  3898. if(typeof(rulesData.hideBar)=="undefined"){
  3899. rulesData.hideBar=false;
  3900. }
  3901. if(typeof(rulesData.dbClick2Stop)=="undefined"){
  3902. rulesData.dbClick2Stop=true;
  3903. }
  3904. if(typeof(rulesData.enableWhiteList)=="undefined"){
  3905. rulesData.enableWhiteList=false;
  3906. }
  3907. if(typeof(rulesData.enableHistory)=="undefined"){
  3908. rulesData.enableHistory=false;
  3909. }
  3910. if(typeof(rulesData.openInNewTab)=="undefined"){
  3911. rulesData.openInNewTab=true;
  3912. }
  3913. if(typeof(rulesData.enableDebug)=="undefined"){
  3914. rulesData.enableDebug=true;
  3915. }
  3916. if(typeof(rulesData.initRun)=="undefined"){
  3917. rulesData.initRun=true;
  3918. }
  3919. if(typeof(rulesData.preload)=="undefined"){
  3920. rulesData.preload=true;
  3921. }
  3922. if(typeof(rulesData.manualMode)=="undefined"){
  3923. rulesData.manualMode=false;
  3924. }
  3925. if(typeof(rulesData.clickMode)=="undefined"){
  3926. rulesData.clickMode=false;
  3927. }
  3928. if(typeof(rulesData.pageBarMenu)=="undefined"){
  3929. rulesData.pageBarMenu=false;
  3930. }
  3931. if(typeof(rulesData.arrowToScroll)=="undefined"){
  3932. rulesData.arrowToScroll=false;
  3933. }
  3934. if(typeof(rulesData.hideLoadingIcon)=="undefined"){
  3935. rulesData.hideLoadingIcon=false;
  3936. }
  3937. if(rulesData.blacklist && rulesData.blacklist.length>0){
  3938. for(let b in rulesData.blacklist){
  3939. let curGlob=rulesData.blacklist[b];
  3940. if(globMatch(curGlob, location.href)){
  3941. return;
  3942. }
  3943. }
  3944. }
  3945. if(rulesData.autoLoadNum){
  3946. autoLoadNum=parseInt(rulesData.autoLoadNum);
  3947. }
  3948. enableDebug=rulesData.enableDebug;
  3949. storage.getItem("nextSwitch_"+location.host, i=>{
  3950. storage.getItem("forceState_"+location.host, v=>{
  3951. storage.getItem("ruleLastUpdate", date=>{
  3952. if(typeof(i)!=="undefined"){
  3953. nextIndex=i;
  3954. }
  3955. if(typeof(v)=="undefined"){
  3956. v=(rulesData.enableWhiteList?1:0);
  3957. }
  3958. forceState=v;
  3959. updateDate=date;
  3960. if(initConfig())return;
  3961. if(forceState==1)return;
  3962. let now=new Date().getTime();
  3963. if(!date || now-date>2*24*60*60*1000){
  3964. updateRules(()=>{
  3965. },(rule,err)=>{});
  3966. storage.setItem("ruleLastUpdate", now);
  3967. }
  3968. callback();
  3969. });
  3970. });
  3971. });
  3972. });
  3973. });
  3974. }
  3975.  
  3976. function requestDoc(url, callback){
  3977. let postParams = url.match(/#p{(.*)}$/);
  3978. if (postParams) {
  3979. postParams = postParams[1];
  3980. url = url.replace(/#p{.*/, "");
  3981. }
  3982. _GM_xmlhttpRequest({
  3983. url: url,
  3984. method: postParams ? 'POST' : 'GET',
  3985. data: postParams,
  3986. overrideMimeType: 'text/html;charset=' + (document.characterSet || document.charset || document.inputEncoding),
  3987. headers: {
  3988. 'Referer': location.href,
  3989. 'User-Agent': navigator.userAgent,
  3990. "Content-Type": (postParams ? "application/x-www-form-urlencoded" : "text/html") + ";charset=" + (document.characterSet || document.charset || document.inputEncoding),
  3991. },
  3992. timeout: 10000,
  3993. onload: function(res) {
  3994. var doc=null,response=res.response;
  3995. let preCode=ruleParser.curSiteRule.pageElementPre || ruleParser.curSiteRule.pagePre;
  3996. if(preCode){
  3997. try{
  3998. if (typeof _unsafeWindow.pagetualPagePre!='undefined') {
  3999. response = _unsafeWindow.pagetualPagePre(response);
  4000. } else if (preCode.length == 2) {
  4001. response = response.replace(new RegExp(preCode[0], "gi"), preCode[1]);
  4002. } else {
  4003. response = Function("response",'"use strict";' + preCode)(response);
  4004. }
  4005. }catch(e){
  4006. debug(e);
  4007. }
  4008. }
  4009. try {
  4010. doc=document.implementation.createHTMLDocument('');
  4011. doc.documentElement.innerHTML=response;
  4012. let base=doc.querySelector("base");
  4013. ruleParser.basePath=base?base.href:url;
  4014. }
  4015. catch (e) {
  4016. debug('parse error'+e.toString());
  4017. }
  4018. let pageElement=ruleParser.getPageElement(doc);
  4019. if(inCors && (!pageElement || pageElement.length==0)){
  4020. ruleParser.curSiteRule.pageElement=allOfBody;
  4021. pageElement=ruleParser.getPageElement(doc);
  4022. ruleParser.getInsert(true);
  4023. }
  4024. //只有1的話怕不是圖片哦
  4025. if(pageElement && (pageElement.length>1 || (pageElement.length==1 && pageElement[0].tagName!="IMG") )){
  4026. ruleParser.insertPage(doc, pageElement, url, callback, false);
  4027. if(ruleParser.curSiteRule.action==1){
  4028. requestFromIframe(url, (doc, eles)=>{
  4029. loadPageOver();
  4030. if(eles){
  4031. ruleParser.insertPage(doc, eles, url, callback, true);
  4032. }
  4033. });
  4034. }else ruleParser.curSiteRule.action=0;
  4035. }else if(ruleParser.curSiteRule.singleUrl || curPage==1){
  4036. ruleParser.curSiteRule.action=1;
  4037. requestFromIframe(url, (doc, eles)=>{
  4038. loadPageOver();
  4039. if(eles){
  4040. ruleParser.insertPage(doc, eles, url, callback, true);
  4041. }
  4042. });
  4043. }else{
  4044. debug("Stop as no page element");
  4045. isPause=true;
  4046. callback(false);
  4047. }
  4048. },
  4049. onerror: function(e){
  4050. debug(e);
  4051. callback(false);
  4052. },
  4053. ontimeout: function(e){
  4054. debug(e);
  4055. callback(false);
  4056. }
  4057. });
  4058. }
  4059.  
  4060. function initPage(){
  4061. ruleParser.initPage(()=>{
  4062. if(ruleParser.curSiteRule.autoLoadNum){
  4063. autoLoadNum=ruleParser.curSiteRule.autoLoadNum;
  4064. }
  4065. if(ruleParser.curSiteRule.nextLink && Array && Array.isArray && Array.isArray(ruleParser.curSiteRule.nextLink)){
  4066. _GM_registerMenuCommand(i18n("nextSwitch"), ()=>{
  4067. NextSwitch.getInstance().start();
  4068. });
  4069. }
  4070. if(ruleParser.nextLinkHref){
  4071. let isJs=/^(javascript|#)/.test(ruleParser.nextLinkHref.replace(location.href,""));
  4072. if(!isJs){
  4073. let inForce=(forceState == 2 || forceState == 3);
  4074. _GM_registerMenuCommand(i18n(inForce?"cancelForceIframe":"forceIframe"), ()=>{
  4075. if(inForce){
  4076. storage.setItem("forceState_"+location.host, "");
  4077. }else{
  4078. let _state=ruleParser.curSiteRule.action>0 || confirm(i18n("forceAllBody"))?2:3;
  4079. storage.setItem("forceState_"+location.host, _state);
  4080. }
  4081. location.reload();
  4082. });
  4083. }
  4084. _GM_registerMenuCommand(i18n("loadNow"), ()=>{
  4085. let loadNum=window.prompt(i18n("loadConfirm"), "1");
  4086. if(loadNum==="" || loadNum===null)return;
  4087. autoLoadNum=Math.abs(parseInt(loadNum));
  4088. nextPage();
  4089. });
  4090. }
  4091. initListener();
  4092. let initRun = typeof ruleParser.curSiteRule.initRun == 'undefined' ? rulesData.initRun : ruleParser.curSiteRule.initRun;
  4093. if (initRun && initRun != 0 && initRun != '0') nextPage();
  4094. });
  4095. }
  4096.  
  4097. var pageBarStyle;
  4098. function initView(){
  4099. _GM_addStyle(`
  4100. .pagetual_pageBar{
  4101. -moz-transition:opacity 0.3s ease-in-out 0s;
  4102. -webkit-transition:opacity 0.3s ease-in-out 0s;
  4103. transition:opacity 0.3s ease-in-out 0s;
  4104. font-family: Arial,sans-serif !important;
  4105. }
  4106. .pagetual_pageBar.stop {
  4107. -webkit-filter: invert(100%);
  4108. filter: invert(100%);
  4109. opacity: 1!important;
  4110. }
  4111. .pagetual_pageBar.hide {
  4112. display: none!important;
  4113. }
  4114. .pagetual_pageBar:hover {
  4115. opacity: 1!important;
  4116. }
  4117. .pagetual_pageBar span {
  4118. vertical-align: super;
  4119. }
  4120. .pagetual_pageBar a::before,
  4121. .pagetual_pageBar a::after {
  4122. content: none;
  4123. }
  4124. .pagetual_pageBar a>span {
  4125. margin-top: 0!important;
  4126. pointer-events: none;
  4127. padding: unset;
  4128. opacity: 0;
  4129. -moz-transition:all 0.3s ease-in-out 0s;
  4130. -webkit-transition:all 0.3s ease-in-out 0s;
  4131. transition:all 0.3s ease-in-out 0s;
  4132. }
  4133. .pagetual_pageBar a>span:hover {
  4134. color: red;
  4135. }
  4136. .pagetual_pageBar a:hover>span {
  4137. opacity: 1;
  4138. }
  4139. .pagetual_pageBar span.prevScreen,
  4140. .pagetual_pageBar span.nextScreen {
  4141. display: block!important;
  4142. }
  4143. .pagetual_pageBar a:hover>span.prevScreen {
  4144. margin-top: -30px!important;
  4145. pointer-events: all;
  4146. }
  4147. .pagetual_pageBar a:hover>span.nextScreen {
  4148. margin-top: 30px!important;
  4149. pointer-events: all;
  4150. }
  4151. .pagetual_pageBar span>svg {
  4152. -moz-transition:transform 0.5s ease, opacity 0.3s ease;
  4153. -webkit-transition:transform 0.5s ease, opacity 0.3s ease;
  4154. transition:transform 0.5 ease, opacity 0.3s ease;
  4155. opacity: 0;
  4156. }
  4157. .pagetual_pageBar:hover span>svg {
  4158. opacity: 1;
  4159. }
  4160. .pagetual_pageBar span>svg.upSvg:hover {
  4161. transform: rotate(360deg) scale3d(1.2, 1.2, 1.2);
  4162. }
  4163. .pagetual_pageBar span>svg.downSvg:hover {
  4164. transform: rotate(540deg) scale3d(1.2, 1.2, 1.2)!important;
  4165. }
  4166. .pagetual_pageBar .pagetual_pageNum{
  4167. color: #55555f;
  4168. }
  4169. .pagetual_pageBar .pagetual_pageNum:hover{
  4170. color: #ff6464;
  4171. }
  4172. .pagetual_tipsWords{
  4173. font-size: 50px;
  4174. font-weight: bold;
  4175. font-family: "黑体", -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto",
  4176. "Oxygen", "Ubuntu", "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji",
  4177. "Segoe UI Emoji", "Segoe UI Symbol";
  4178. color: #ffffff;
  4179. min-height: 70px;
  4180. max-width: 80%;
  4181. line-height: 70px;
  4182. position: fixed;
  4183. left: 50%;
  4184. top: 10%;
  4185. margin-left: -99999px;
  4186. padding: 0 15px;
  4187. z-index: 999999999;
  4188. background-color: #000;
  4189. border: 1px solid #303030;
  4190. border-radius: 10px;
  4191. opacity: 0;
  4192. filter: alpha(opacity=65);
  4193. box-shadow: 5px 5px 20px 0px #000;
  4194. -moz-transition:opacity 0.3s ease-in-out 0s;
  4195. -webkit-transition:opacity 0.3s ease-in-out 0s;
  4196. transition:opacity 0.3s ease-in-out 0s;
  4197. pointer-events: none;
  4198. }
  4199. .pagetual_loading {
  4200. width: 50px;
  4201. height: 50px;
  4202. margin: 10px auto;
  4203. border-radius: 100%;
  4204. display: flex;
  4205. -webkit-animation: pagetual_loading_scaleout 1.0s infinite ease-in-out;
  4206. animation: pagetual_loading_scaleout 1.0s infinite ease-in-out;
  4207. }
  4208. @-webkit-keyframes pagetual_loading_scaleout {
  4209. 0% { -webkit-transform: scale(0.0) }
  4210. 100% {
  4211. -webkit-transform: scale(1.0);
  4212. opacity: 0;
  4213. }
  4214. }
  4215. @keyframes pagetual_loading_scaleout {
  4216. 0% {
  4217. transform: scale(0.0);
  4218. -webkit-transform: scale(0.0);
  4219. } 100% {
  4220. transform: scale(1.0);
  4221. -webkit-transform: scale(1.0);
  4222. opacity: 0;
  4223. }
  4224. }
  4225. .pagetual_loading_text {
  4226. white-space: nowrap;
  4227. -webkit-animation: pagetual_loading_opacity 2.6s infinite ease-in-out;
  4228. animation: pagetual_loading_opacity 2.6s infinite ease-in-out;
  4229. }
  4230. @-webkit-keyframes pagetual_loading_opacity {
  4231. 0% { opacity: 1 }
  4232. 50% { opacity: 0.2 }
  4233. 100% { opacity: 1 }
  4234. }
  4235. @keyframes pagetual_loading_opacity {
  4236. 0% { opacity: 1 }
  4237. 50% { opacity: 0.2 }
  4238. 100% { opacity: 1 }
  4239. }
  4240. `);
  4241. pageBarStyle=`vertical-align: super;line-height:1;opacity:${rulesData.opacity};display:${rulesData.opacity==0?"none":"inline-flex"};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!important;justify-content: center;`;
  4242. }
  4243. var loadingDiv=document.createElement("div");
  4244. 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;";
  4245.  
  4246. const 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; flex: 0;`;
  4247. function setLoadingDiv(loadingText){
  4248. loadingDiv.innerHTML=`<p class="pagetual_loading_text" style="${loadingCSS}display: inline-block;">${loadingText}</p>${rulesData.hideLoadingIcon ? "" : `<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"><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"></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"></path></svg></div>`}`;
  4249. }
  4250.  
  4251. var upSvg=`<svg width="30" height="30" class="upSvg pagetual" style="display:initial;position:relative;cursor: pointer;margin: 0 8px;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"><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"></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"></path></svg>`;
  4252. var upSvgCSS=`display:initial;position:relative;cursor: pointer;margin: 0 8px;width: 30px;height: 30px;vertical-align: middle;fill: currentColor;overflow: hidden;`;
  4253. var downSvg=`<svg width="30" height="30" class="downSvg pagetual" style="display:initial;position:relative;cursor: pointer;margin: 0 8px;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"><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"></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"></path></svg>`;
  4254. var downSvgCSS=`display:initial;position:relative;cursor: pointer;margin: 0 8px;width: 30px;height: 30px;vertical-align: middle;fill: currentColor;overflow: hidden;transform: rotate(180deg);`;
  4255.  
  4256. const 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 5px;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;`;
  4257. const pageTextStyle=`padding: unset;border: none;background: unset!important;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;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)!important;`;
  4258.  
  4259. var tipsWords=document.createElement("div");
  4260. tipsWords.className="pagetual_tipsWords";
  4261.  
  4262. var isPause = false, isHideBar = false, isLoading = false, curPage = 1, forceState = 0, bottomGap = 1000, autoLoadNum = -1, nextIndex = 0, stopScroll = false;
  4263.  
  4264. function changeStop(stop) {
  4265. isPause = stop;
  4266. [].forEach.call(document.querySelectorAll(".pagetual_pageBar"), bar => {
  4267. if (isPause) {
  4268. bar.classList.add("stop");
  4269. } else {
  4270. bar.classList.remove("stop");
  4271. }
  4272. });
  4273. }
  4274.  
  4275. function changeHideBar(hide) {
  4276. isHideBar = hide;
  4277. [].forEach.call(document.querySelectorAll(".pagetual_pageBar"), bar => {
  4278. if (isHideBar) {
  4279. bar.classList.add("hide");
  4280. } else {
  4281. bar.classList.remove("hide");
  4282. }
  4283. });
  4284. }
  4285.  
  4286. function isInViewPort(element) {
  4287. if(!document.body.contains(element))return false;
  4288. if(_unsafeWindow.getComputedStyle(element).display=="none")return false;
  4289. const viewWidth = window.innerWidth || document.documentElement.clientWidth;
  4290. const viewHeight = window.innerHeight || document.documentElement.clientHeight;
  4291. const {
  4292. top,
  4293. right,
  4294. bottom,
  4295. left,
  4296. } = element.getBoundingClientRect();
  4297.  
  4298. return (
  4299. top >= 0 &&
  4300. left >= 0 &&
  4301. right <= viewWidth + 1 &&
  4302. bottom <= viewHeight * 2
  4303. );
  4304. }
  4305.  
  4306. var urlChanged=false;
  4307. var _wr = function(type) {
  4308. var orig = history[type];
  4309. return function() {
  4310. var rv = orig.apply(this, arguments);
  4311. var e = new Event(type);
  4312. e.arguments = arguments;
  4313. window.dispatchEvent(e);
  4314. return rv;
  4315. };
  4316. };
  4317. var changeHandler = e => {
  4318. urlChanged = true;
  4319. isPause = true;
  4320. setTimeout(() => {
  4321. lastActiveUrl = location.href;
  4322. if (location.href == configPage[0] || guidePage.test(location.href)) {
  4323. location.reload();
  4324. } else if (!ruleParser.ruleMatch(ruleParser.curSiteRule)) {
  4325. initPage();
  4326. }
  4327. if (!ruleParser.nextLinkHref) isLoading = false;
  4328. },1);
  4329. };
  4330. history.pushState = _wr('pushState');
  4331. window.addEventListener('pushState', changeHandler);
  4332.  
  4333. function initListener(){
  4334. let loadmoreBtn,loading=true,lastScroll=0,checkLoadMoreTimes=0;
  4335. if (ruleParser.curSiteRule.loadMore) {
  4336. loading=false;
  4337. } else {
  4338. let checkLoadMore=setInterval(()=>{
  4339. loadmoreBtn=getLoadMore(document);
  4340. if(loadmoreBtn && isVisible(loadmoreBtn, _unsafeWindow)){
  4341. loading=false;
  4342. clearInterval(checkLoadMore);
  4343. }else if(checkLoadMoreTimes++>30){
  4344. clearInterval(checkLoadMore);
  4345. }
  4346. },300);
  4347. }
  4348. let clickMode = typeof ruleParser.curSiteRule.clickMode == 'undefined' ? rulesData.clickMode : ruleParser.curSiteRule.clickMode;
  4349. let clickNext = async () => {
  4350. let nextLink = ruleParser.nextLinkHref;
  4351. if (!nextLink) return;
  4352. let isJs = /^(javascript|#)/.test(nextLink.replace(location.href, ""));
  4353. if (isJs) {
  4354. let nextBtn = await ruleParser.getNextLink(document);
  4355. if (nextBtn) emuClick(nextBtn);
  4356. } else {
  4357. window.location.href = nextLink;
  4358. }
  4359. };
  4360. let checkScrollReach=()=>{
  4361. let scrolly=window.scrollY;
  4362. let windowHeight=window.innerHeight || document.documentElement.clientHeight;
  4363. let scrollH=Math.max(document.documentElement.scrollHeight, document.body.scrollHeight);
  4364. if(clickMode){
  4365. if(scrollH-scrolly-windowHeight<10){
  4366. clickNext();
  4367. }
  4368. }else if(scrollH-scrolly-windowHeight<bottomGap){
  4369. nextPage();
  4370. }
  4371. };
  4372. let scrollHandler = e=>{
  4373. if(urlChanged && !isLoading){
  4374. ruleParser.initPage(()=>{
  4375. if(ruleParser.nextLinkHref){
  4376. initView();
  4377. }
  4378. isPause=false;
  4379. });
  4380. urlChanged=false;
  4381. }
  4382. if(isPause)return;
  4383. if(!loading){
  4384. if(ruleParser.curSiteRule.loadMore || !loadmoreBtn || !document.body.contains(loadmoreBtn)){
  4385. loadmoreBtn=getLoadMore(document);
  4386. }
  4387. if(loadmoreBtn){
  4388. if(isInViewPort(loadmoreBtn)){
  4389. emuClick(loadmoreBtn);
  4390. loading=true;
  4391. setTimeout(()=>{loading=false},200);
  4392. }
  4393. }else{
  4394. loading=true;
  4395. setTimeout(()=>{loading=false},200);
  4396. }
  4397. }
  4398. if(!isLoading && !stopScroll){
  4399. checkScrollReach();
  4400. }
  4401. if(ruleParser.curSiteRule.lockScroll){
  4402. let curScroll=document.body.scrollTop||document.documentElement.scrollTop;
  4403. if(isLoading && Math.abs(lastScroll-curScroll)>350){
  4404. document.body.scrollTop=lastScroll;
  4405. document.documentElement.scrollTop=lastScroll;
  4406. }else{
  4407. lastScroll=curScroll;
  4408. }
  4409. }
  4410. };
  4411. document.addEventListener('dblclick', e=>{
  4412. if(forceState==1 || e.target.tagName=='INPUT' || e.target.tagName=='TEXTAREA') return;
  4413. if(!rulesData.dbClick2StopKey){
  4414. if((rulesData.dbClick2StopCtrl && !e.ctrlKey) ||
  4415. (rulesData.dbClick2StopAlt && !e.altKey) ||
  4416. (rulesData.dbClick2StopShift && !e.shiftKey) ||
  4417. (rulesData.dbClick2StopMeta && !e.metaKey)){
  4418. return;
  4419. }
  4420. }
  4421. if(e.target.tagName !== "BODY" && e.target.className !== 'pagetual_pageBar'){
  4422. let selStr=document.getSelection().toString();
  4423. if(selStr && selStr.trim()){
  4424. return;
  4425. }
  4426. }
  4427. if(rulesData.dbClick2Stop && (ruleParser.nextLinkHref || loadmoreBtn)){
  4428. setTimeout(()=>{
  4429. if (rulesData.hideBarButNoStop || rulesData.hideBar) {
  4430. changeHideBar(!isHideBar);
  4431. }
  4432. if (!rulesData.hideBarButNoStop) {
  4433. changeStop(!isPause);
  4434. showTips(i18n(isPause?"disable":"enable"));
  4435. }
  4436. if(!isPause){
  4437. checkScrollReach();
  4438. }
  4439. },10);
  4440. }
  4441. });
  4442. if(rulesData.dbClick2StopKey){
  4443. document.addEventListener('keydown', e=>{
  4444. if((rulesData.dbClick2StopCtrl && !e.ctrlKey) ||
  4445. (rulesData.dbClick2StopAlt && !e.altKey) ||
  4446. (rulesData.dbClick2StopShift && !e.shiftKey) ||
  4447. (rulesData.dbClick2StopMeta && !e.metaKey)){
  4448. return;
  4449. }
  4450. if (document.activeElement &&
  4451. (document.activeElement.tagName == 'INPUT' ||
  4452. document.activeElement.tagName == 'TEXTAREA')) {
  4453. return;
  4454. }
  4455. var key = e.key.toLowerCase();
  4456. if(rulesData.dbClick2StopKey.toLowerCase()==key){
  4457. forceState=(forceState==1?0:1);
  4458. showTips(i18n(forceState==1?"disableSiteTips":"enableSiteTips"));
  4459. if(!ruleParser.curSiteRule.url) {
  4460. storage.setItem("forceState_"+location.host, forceState);
  4461. location.reload();
  4462. }
  4463. }
  4464. });
  4465. }
  4466. if (ruleParser.curSiteRule.listenHashChange) {
  4467. window.addEventListener('hashchange', () => {
  4468. urlChanged = true;
  4469. isPause = true;
  4470. if (!ruleParser.nextLinkHref) isLoading = false;
  4471. }, false);
  4472. }
  4473. let manualMode = typeof ruleParser.curSiteRule.manualMode == 'undefined' ? rulesData.manualMode : ruleParser.curSiteRule.manualMode;
  4474. if (manualMode) {
  4475. document.addEventListener('keydown', e => {
  4476. if (document.activeElement &&
  4477. (document.activeElement.tagName == 'INPUT' ||
  4478. document.activeElement.tagName == 'TEXTAREA' ||
  4479. document.activeElement.contentEditable == 'true')) {
  4480. return;
  4481. }
  4482. if(e.keyCode == 39){
  4483. clickNext();
  4484. }
  4485. });
  4486. document.addEventListener('pagetual.next', function() {
  4487. clickNext();
  4488. }, false);
  4489. return;
  4490. }
  4491. if (rulesData.arrowToScroll) {
  4492. let getPageBar = () => {
  4493. let preBar = null, nextBar = null;
  4494. let pageBars = [].slice.call(document.querySelectorAll(".pagetual_pageBar"));
  4495. for (let i = 0; i < pageBars.length; i++) {
  4496. let pageBar = pageBars[i];
  4497. if (!pageBar || !document.body.contains(pageBar)) continue;
  4498. let {
  4499. top,
  4500. right,
  4501. bottom,
  4502. left,
  4503. } = pageBar.getBoundingClientRect();
  4504. if (top > 500) {
  4505. nextBar = pageBar;
  4506. preBar = (i - 1 >= 0 ? pageBars[i - 1] : null);
  4507. if (pageBar && document.body.contains(pageBar)) {
  4508. let {
  4509. top,
  4510. right,
  4511. bottom,
  4512. left,
  4513. } = pageBar.getBoundingClientRect();
  4514. if (top < -500) {
  4515. preBar = pageBar;
  4516. } else preBar = (i - 2 >= 0 ? pageBars[i - 2] : null);
  4517. }
  4518. break;
  4519. }
  4520. }
  4521. if (!nextBar) preBar = pageBars[pageBars.length - 2];
  4522. return {preBar: preBar, nextBar: nextBar};
  4523. };
  4524. document.addEventListener('keyup', e => {
  4525. if (document.activeElement &&
  4526. (document.activeElement.tagName == 'INPUT' ||
  4527. document.activeElement.tagName == 'TEXTAREA' ||
  4528. document.activeElement.contentEditable == 'true')) {
  4529. return;
  4530. }
  4531. if (e.keyCode == 39) {
  4532. let nextPageBar=getPageBar().nextBar;
  4533. if (nextPageBar) {
  4534. scrollToPageBar(nextPageBar);
  4535. } else {
  4536. let scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
  4537. window.scrollTo({ top: scrollTop + (window.innerHeight || document.documentElement.clientHeight), behavior: 'smooth'});
  4538. }
  4539. } else if (e.keyCode == 37) {
  4540. let prePageBar = getPageBar().preBar;
  4541. if (prePageBar) {
  4542. scrollToPageBar(prePageBar);
  4543. } else {
  4544. let scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
  4545. window.scrollTo({ top: scrollTop - (window.innerHeight || document.documentElement.clientHeight), behavior: 'smooth'});
  4546. }
  4547. }
  4548. });
  4549. }
  4550. if (!ruleParser.curSiteRule.wheel) {
  4551. document.addEventListener('scroll', scrollHandler, true);
  4552. }
  4553. document.addEventListener('wheel', scrollHandler, true);
  4554. }
  4555.  
  4556. function showTips(content, wordColor, backColor){
  4557. document.body.appendChild(tipsWords);
  4558. tipsWords.style.opacity=0.8;
  4559. tipsWords.innerText=content;
  4560. tipsWords.style.marginLeft=-tipsWords.offsetWidth/2+"px";
  4561. tipsWords.style.color=wordColor||0xFFFFFF;
  4562. tipsWords.style.backgroundColor=backColor||0x000;
  4563. setTimeout(()=>{tipsWords.style.opacity=0},1000);
  4564. }
  4565.  
  4566. function getLoadMore(doc) {
  4567. if (ruleParser.curSiteRule.loadMore === "") return null;
  4568. let btnSel = ruleParser.curSiteRule.loadMore || ".LoadMore,.load-more,.button-show-more,button[data-testid='more-results-button']", loadmoreBtn;
  4569. if (btnSel) {
  4570. loadmoreBtn = getElement(btnSel, doc);
  4571. }
  4572. if (!loadmoreBtn) {
  4573. let buttons = doc.querySelectorAll("input,button,a,div[onclick]"), loadmoreReg = /^\s*(加载更多|加載更多|load\s*more|もっと読み込む)\s*$/i;
  4574. for (let i = 0; i < buttons.length; i++) {
  4575. let button = buttons[i];
  4576. if (button.innerText.length > 20) continue;
  4577. if (button && loadmoreReg.test(button.innerText)) {
  4578. loadmoreBtn = button;
  4579. break;
  4580. }
  4581. }
  4582. }
  4583. if (loadmoreBtn && !ruleParser.curSiteRule.loadMore && loadmoreBtn.dataset.ajax !== "true") {
  4584. let href = loadmoreBtn.getAttribute("href");
  4585. if (href && href != "/" && !/^(javascript|#)/.test(href.replace(location.href,""))) {
  4586. loadmoreBtn = null;
  4587. }
  4588. }
  4589. return loadmoreBtn;
  4590. }
  4591.  
  4592. function scrollToPageBar(bar){
  4593. let yOffset = -20;
  4594. if (typeof ruleParser.curSiteRule.pageBarTop !== 'undefined') {
  4595. yOffset = -ruleParser.curSiteRule.pageBarTop;
  4596. }
  4597. const y = bar.getBoundingClientRect().top + window.pageYOffset + yOffset;
  4598. window.scrollTo({ top: y, behavior: 'smooth'});
  4599. }
  4600.  
  4601. const pageNumReg=/[&\/\?](p=|page[=\/_-]?)\d+|[_-]\d+\./;
  4602. function createPageBar(url) {
  4603. url = url.replace(/#p{.*/, "");
  4604. if (rulesData.opacity == 0 || ruleParser.curSiteRule.pageBar === 0) return null;
  4605. let insert=ruleParser.getInsert();
  4606. if(!insert || !insert.parentNode)return;
  4607. curPage++;
  4608. let example=ruleParser.curSiteRule.insertPos==2?insert.children[0]:(insert.parentNode.children[parseInt(insert.parentNode.children.length/2)]||insert);
  4609. if (example.className=="pagetual_pageBar") {
  4610. example=example.previousElementSibling;
  4611. }
  4612. if(!example || !example.parentNode)example=insert;
  4613. let exampleStyle = _unsafeWindow.getComputedStyle(example);
  4614. let inTable, inLi;
  4615. if (forceState == 2) {
  4616. inTable = inLi = false;
  4617. } else {
  4618. inTable=example.parentNode.tagName=="TABLE" ||
  4619. example.parentNode.tagName=="TBODY" ||
  4620. example.tagName=="TR" ||
  4621. example.tagName=="TBODY" ||
  4622. exampleStyle.display=="table-row" ||
  4623. (example.previousElementSibling && example.previousElementSibling.tagName=="TR") ||
  4624. (example.previousElementSibling && example.previousElementSibling.tagName=="TBODY");
  4625. inLi=example.tagName=="LI" || (example.previousElementSibling && example.previousElementSibling.tagName=="LI");
  4626. }
  4627. let pageBar=document.createElement(inTable?"tr":(inLi?"li":"div"));
  4628. let upSpan=document.createElement("span");
  4629. let downSpan=document.createElement("span");
  4630. let pageText=document.createElement("a");
  4631. let pageNum;
  4632. let scrollH=Math.max(document.documentElement.scrollHeight, document.body.scrollHeight);
  4633. pageBar.className=isHideBar?"pagetual_pageBar hide":"pagetual_pageBar";
  4634. pageBar.id="pagetual_pageBar"+curPage;
  4635. pageBar.setAttribute("translate", "no");
  4636. if(isPause){
  4637. pageBar.classList.add("stop");
  4638. }
  4639. pageBar.style.cssText=pageBarStyle;
  4640. pageBar.title=i18n(isPause?"enable":"disable");
  4641. upSpan.innerHTML=upSvg;
  4642. upSpan.children[0].style.cssText=upSvgCSS;
  4643. upSpan.title=i18n("toTop");
  4644. downSpan.innerHTML=downSvg;
  4645. downSpan.children[0].style.cssText=downSvgCSS;
  4646. downSpan.title=i18n("toBottom");
  4647. upSpan.style.cssText=initStyle;
  4648. downSpan.style.cssText=initStyle;
  4649. pageText.href=url;
  4650. pageText.style.cssText=pageTextStyle;
  4651. pageText.title=i18n("current");
  4652. if(rulesData.openInNewTab)pageText.target="_blank";
  4653. pageBar.appendChild(upSpan);
  4654. pageBar.appendChild(pageText);
  4655. if(rulesData.pageBarMenu){
  4656. pageText.addEventListener("click", e=>{
  4657. e.stopPropagation();
  4658. if (e.ctrlKey || e.altKey || e.shiftKey || e.metaKey) return;
  4659. e.preventDefault();
  4660. Picker.getInstance().start();
  4661. });
  4662. }
  4663. let touched = false;
  4664. let touchBodyHandler = e => {
  4665. touched = false;
  4666. document.body.removeEventListener('touchstart', touchBodyHandler);
  4667. };
  4668. pageText.addEventListener("touchstart", e => {
  4669. if (touched) return;
  4670. touched = true;
  4671. pageText.style.pointerEvents = 'none';
  4672. setTimeout(() => {
  4673. pageText.style.pointerEvents = 'all';
  4674. }, 250);
  4675. document.body.addEventListener("touchstart", touchBodyHandler);
  4676. });
  4677. if(ruleParser.nextTitle){
  4678. pageText.innerHTML=ruleParser.nextTitle+" ";
  4679. pageText.title=ruleParser.nextTitle;
  4680. }
  4681. if(ruleParser.curSiteRule.pageNum || pageNumReg.test(url)){
  4682. pageText.innerHTML+="Page ";
  4683. pageNum=document.createElement("span");
  4684. pageNum.innerHTML=ruleParser.getPageNumFromUrl(url);
  4685. pageNum.className="pagetual_pageNum";
  4686. pageNum.title=i18n("inputPageNum");
  4687. pageNum.style.cssText=pageTextStyle;
  4688. pageNum.style.cursor="pointer";
  4689. pageNum.style.color="";
  4690. pageNum.style.marginLeft="5px";
  4691. pageNum.addEventListener("click", e=>{
  4692. let pageInput=prompt(i18n("inputPageNum"), "1");
  4693. if(pageInput){
  4694. let pageLink=ruleParser.getLinkByPage(url, pageInput);
  4695. if(pageLink){
  4696. _GM_openInTab(pageLink,{active:true});
  4697. }
  4698. }
  4699. e.preventDefault();
  4700. e.stopPropagation();
  4701. });
  4702. pageBar.appendChild(pageNum);
  4703. }else{
  4704. pageText.innerHTML+="Page "+curPage;
  4705. }
  4706. let preBtn=document.createElement("span");
  4707. preBtn.innerHTML="∧";
  4708. preBtn.title="Prev page";
  4709. preBtn.className="prevScreen";
  4710. preBtn.style.cssText="display: none;text-align: center;right: unset; float: left; margin-top: -30px; width: 40px; background: rgba(240, 240, 240, 0.8); position: absolute; border-radius: 20px 20px 0 0; box-shadow: rgb(0 0 0 / 50%) 0px -5px 5px;z-index:9999999";
  4711. let nextBtn=document.createElement("span");
  4712. nextBtn.innerHTML="∨";
  4713. nextBtn.title="Next page";
  4714. nextBtn.className="nextScreen";
  4715. nextBtn.style.cssText="display: none;text-align: center;right: unset; float: left; margin-top: 30px; width: 40px; background: rgba(240, 240, 240, 0.8); position: absolute; border-radius: 0 0 20px 20px; box-shadow: rgb(0 0 0 / 50%) 0px 5px 5px;z-index:9999999";
  4716. let localPage=curPage;
  4717. preBtn.addEventListener("click", e=>{
  4718. e.stopPropagation();
  4719. e.preventDefault();
  4720. let prePageBar = document.querySelector("#pagetual_pageBar"+(localPage-1));
  4721. if (prePageBar) {
  4722. scrollToPageBar(prePageBar);
  4723. } else {
  4724. let scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
  4725. window.scrollTo({ top: scrollTop - (window.innerHeight || document.documentElement.clientHeight), behavior: 'smooth'});
  4726. }
  4727. });
  4728. nextBtn.addEventListener("click", e=>{
  4729. e.stopPropagation();
  4730. e.preventDefault();
  4731. let nextPageBar=document.querySelector("#pagetual_pageBar"+(localPage+1));
  4732. if (nextPageBar) {
  4733. scrollToPageBar(nextPageBar);
  4734. } else {
  4735. let nextEle = pageBar.parentNode.nextElementSibling;
  4736. if (nextEle) scrollToPageBar(nextEle);
  4737. else {
  4738. scrollH=Math.max(document.documentElement.scrollHeight, document.body.scrollHeight);
  4739. window.scrollTo({ top: scrollH || 9999999, behavior: 'smooth'});
  4740. }
  4741. }
  4742. });
  4743. pageText.insertBefore(preBtn, pageText.firstChild);
  4744. pageText.insertBefore(nextBtn, pageText.firstChild);
  4745. pageBar.appendChild(downSpan);
  4746. if (forceState == 2) {
  4747. pageBar.style.width = "99%";
  4748. } else {
  4749. let parentStyle=_unsafeWindow.getComputedStyle(example.parentNode);
  4750. let parentWidth=example.parentNode.offsetWidth||parseInt(parentStyle.width);
  4751. pageBar.style.width=parentWidth-parseInt(parentStyle.paddingLeft)-parseInt(parentStyle.paddingRight)-10+"px";
  4752. pageBar.style.margin='10px 5px';
  4753. if(parentStyle.display=="grid" || parentStyle.display=="inline-grid"){
  4754. pageBar.style.gridColumnStart=1;
  4755. pageBar.style.gridColumnEnd=1+parseInt(example.parentNode.offsetWidth/example.offsetWidth);
  4756. }
  4757. if(inTable){
  4758. example=(example.tagName=="TR" || example.tagName=="TBODY")?example:example.previousElementSibling;
  4759. if(example.tagName=="TBODY")example=example.querySelector("tr");
  4760. let preTr=example;
  4761. while(preTr && preTr.children.length==0)preTr=preTr.previousElementSibling;
  4762. if(preTr)example=preTr;
  4763. let tdNum=0;
  4764. if (exampleStyle.display=="table-row") {
  4765. [].forEach.call(example.children, el=>{
  4766. tdNum+=el.colSpan||1;
  4767. });
  4768. } else {
  4769. [].forEach.call(example.children, el=>{
  4770. if(el.tagName=="TD" || el.tagName=="TH"){
  4771. tdNum+=el.colSpan||1;
  4772. }
  4773. });
  4774. }
  4775. pageBar.style.display="table-row";
  4776. pageBar.style.backgroundColor="unset";
  4777. pageBar.style.lineHeight="20px";
  4778. pageBar.style.boxShadow="";
  4779. pageBar.style.height="35px";
  4780. let td=document.createElement("td");
  4781. td.colSpan=tdNum||1;
  4782. let inTd=document.createElement("div");
  4783. inTd.style.backgroundColor="rgb(240 240 240 / 80%)";
  4784. inTd.style.borderRadius="20px";
  4785. inTd.style.padding="0 0";
  4786. inTd.style.margin="0";
  4787. inTd.style.lineHeight="20px";
  4788. inTd.style.textAlign="center";
  4789. inTd.style.boxShadow="rgb(0 0 0 / 67%) 0px 0px 10px 0px";
  4790. inTd.appendChild(upSpan);
  4791. inTd.appendChild(pageText);
  4792. if(pageNum)inTd.appendChild(pageNum);
  4793. inTd.appendChild(downSpan);
  4794. td.appendChild(inTd);
  4795. pageBar.appendChild(td);
  4796. }else if(inLi){
  4797. example=example.tagName=="LI"?example:example.previousElementSibling;
  4798. pageBar.style.display=getComputedStyle(example).display;
  4799. pageBar.style.backgroundColor="unset";
  4800. pageBar.style.lineHeight="20px";
  4801. pageBar.style.boxShadow="";
  4802. pageBar.style.height="35px";
  4803. let td=document.createElement("td");
  4804. td.colSpan=example.children.length;
  4805. td.style.width='100%';
  4806. let inTd=document.createElement("div");
  4807. inTd.style.backgroundColor="rgb(240 240 240 / 80%)";
  4808. inTd.style.borderRadius="20px";
  4809. inTd.style.margin="0"
  4810. inTd.style.padding="0 0";
  4811. inTd.style.textAlign="center";
  4812. inTd.style.minWidth="150px";
  4813. inTd.appendChild(upSpan);
  4814. inTd.appendChild(pageText);
  4815. inTd.style.width='calc(100% - 20px)';
  4816. inTd.style.boxShadow="rgb(0 0 0 / 67%) 0px 0px 10px 0px";
  4817. if(pageNum)inTd.appendChild(pageNum);
  4818. inTd.appendChild(downSpan);
  4819. if (pageBar.style.display === 'table-row') {
  4820. td.appendChild(inTd);
  4821. pageBar.appendChild(td);
  4822. } else {
  4823. inTd.style.width='100%';
  4824. pageBar.appendChild(inTd);
  4825. }
  4826. }
  4827. }
  4828.  
  4829. upSpan.addEventListener("click", e=>{
  4830. document.body.scrollTop=0;
  4831. document.documentElement.scrollTop=0;
  4832. e.preventDefault();
  4833. e.stopPropagation();
  4834. });
  4835. downSpan.addEventListener("click", e=>{
  4836. changeStop(true);
  4837. pageBar.title = i18n(isPause ? "enable" : "disable");
  4838. scrollH=Math.max(document.documentElement.scrollHeight, document.body.scrollHeight);
  4839. document.body.scrollTop = scrollH || 9999999;
  4840. document.documentElement.scrollTop = scrollH || 9999999;
  4841. e.preventDefault();
  4842. e.stopPropagation();
  4843. });
  4844. pageBar.addEventListener("click", e=>{
  4845. changeStop(!isPause);
  4846. pageBar.title=i18n(isPause?"enable":"disable");
  4847. });
  4848. ruleParser.insertElement(pageBar);
  4849. if(ruleParser.curSiteRule.pageBar && ruleParser.curSiteRule.pageBar !== 0){
  4850. try{
  4851. ((typeof _unsafeWindow.pagetualPageBar=='undefined') ? Function("pageBar",'"use strict";' + ruleParser.curSiteRule.pageBar) : _unsafeWindow.pagetualPageBar)(pageBar);
  4852. }catch(e){
  4853. debug(e);
  4854. }
  4855. }
  4856.  
  4857. let posEle=pageBar.nextElementSibling||pageBar;
  4858. while(posEle && !posEle.offsetParent){
  4859. posEle=posEle.previousElementSibling||posEle.parentNode;
  4860. }
  4861. if(posEle){
  4862. let actualTop = getElementTop(posEle);
  4863. bottomGap=scrollH-actualTop+(window.innerHeight||document.documentElement.clientHeight)*(ruleParser.curSiteRule.rate||1);
  4864. if(bottomGap<100)bottomGap=100;
  4865. }else{
  4866. bottomGap=1000;
  4867. }
  4868. return pageBar;
  4869. }
  4870.  
  4871. function emuClick(btn){
  4872. let orgHref=btn.getAttribute('href');
  4873. if(orgHref){
  4874. btn.setAttribute('href', orgHref.replace(/#$/,""));
  4875. }
  4876. if(!PointerEvent)return btn.click();
  4877. let eventParam={
  4878. isTrusted: true,
  4879. altKey: false,
  4880. azimuthAngle: 0,
  4881. bubbles: true,
  4882. button: 0,
  4883. buttons: 0,
  4884. clientX: 1,
  4885. clientY: 1,
  4886. cancelBubble: false,
  4887. cancelable: true,
  4888. composed: true,
  4889. ctrlKey: false,
  4890. defaultPrevented: false,
  4891. detail: 1,
  4892. eventPhase: 2,
  4893. fromElement: null,
  4894. height: 1,
  4895. isPrimary: false,
  4896. metaKey: false,
  4897. pointerId: 1,
  4898. pointerType: "mouse",
  4899. pressure: 0,
  4900. relatedTarget: null,
  4901. returnValue: true,
  4902. shiftKey: false,
  4903. toElement: null,
  4904. twist: 0,
  4905. which: 1
  4906. };
  4907. let mouseEvent = new PointerEvent("mousedown",eventParam);
  4908. btn.dispatchEvent(mouseEvent);
  4909. mouseEvent = new PointerEvent("mouseup",eventParam);
  4910. btn.dispatchEvent(mouseEvent);
  4911. let dispatchTouchEvent = (ele, type) => {
  4912. let touchEvent;
  4913. try {
  4914. touchEvent = document.createEvent('TouchEvent')
  4915. touchEvent.initTouchEvent(type, true, true)
  4916. } catch (err) {
  4917. try {
  4918. touchEvent = document.createEvent('UIEvent')
  4919. touchEvent.initUIEvent(type, true, true)
  4920. } catch (err) {
  4921. touchEvent = document.createEvent('Event')
  4922. touchEvent.initEvent(type, true, true)
  4923. }
  4924. }
  4925. touchEvent.targetTouches = [{
  4926. pageX: 1,
  4927. pageY: 1,
  4928. clientX: 1,
  4929. clientY: 1,
  4930. target: btn
  4931. }];
  4932. touchEvent.touches = [{
  4933. pageX: 1,
  4934. pageY: 1,
  4935. clientX: 1,
  4936. clientY: 1,
  4937. target: btn
  4938. }];
  4939. touchEvent.changedTouches = [{
  4940. pageX: 1,
  4941. pageY: 1,
  4942. clientX: 1,
  4943. clientY: 1,
  4944. target: btn
  4945. }];
  4946. ele.dispatchEvent(touchEvent);
  4947. }
  4948. dispatchTouchEvent(btn, "touchstart");
  4949. dispatchTouchEvent(btn, "touchend");
  4950.  
  4951. btn.click();
  4952. if(orgHref){
  4953. setTimeout(()=>btn.setAttribute('href', orgHref),0);
  4954. }
  4955. }
  4956.  
  4957. var failFromIframe=0;
  4958. var inCors=false;
  4959. var checkRemoveIntv;
  4960. function requestFromIframe(url, callback){
  4961. url = url.indexOf('=') == -1 ? url.replace(/#[^#]*/,"") : url;
  4962. let iframe = document.createElement('iframe');
  4963. iframe.name = 'pagetual-iframe';
  4964. iframe.width = '100%';
  4965. iframe.height = '1000';
  4966. iframe.frameBorder = '0';
  4967. if(ruleParser.curSiteRule.sandbox!=false){
  4968. iframe.sandbox="allow-same-origin allow-scripts allow-popups allow-forms";
  4969. }
  4970. iframe.style.cssText = 'margin:0!important;padding:0!important;visibility:hidden!important;flex:0;opacity:0!important;pointer-events:none!important;position:fixed;top:0px;left:0px;z-index:-2147483647;';
  4971. let waitTime=100,checkEval;
  4972. if(ruleParser.curSiteRule.waitElement){
  4973. checkEval = doc => {
  4974. return ruleParser.waitElement(doc);
  4975. };
  4976. }else if(ruleParser.curSiteRule.wait){
  4977. if(isNaN(ruleParser.curSiteRule.wait)){
  4978. try{
  4979. checkEval=(typeof _unsafeWindow.pagetualWait=='undefined') ? Function("doc",'"use strict";' + ruleParser.curSiteRule.wait) : _unsafeWindow.pagetualWait;
  4980. }catch(e){
  4981. debug(e);
  4982. }
  4983. }else{
  4984. waitTime=ruleParser.curSiteRule.wait;
  4985. }
  4986. }
  4987. if (checkRemoveIntv) clearInterval(checkRemoveIntv);
  4988. checkRemoveIntv = setInterval(() => {
  4989. if (!iframe || !document.body.contains(iframe)) {
  4990. clearInterval(checkRemoveIntv);
  4991. loadPageOver();
  4992. }
  4993. }, 500);
  4994. let loadedHandler = e => {
  4995. if(e.data != 'pagetual-iframe:DOMLoaded' && e.type != 'load')return;
  4996. clearInterval(checkRemoveIntv);
  4997. window.removeEventListener('message', loadedHandler, false);
  4998. iframe.removeEventListener('load', loadedHandler, false);
  4999. let tryTimes=0;
  5000. function checkIframe(){
  5001. if (urlChanged || isPause) {
  5002. return callback(false, false);
  5003. }
  5004. try{
  5005. let doc=iframe.contentDocument || iframe.contentWindow.document;
  5006. let base=doc.querySelector("base");
  5007. ruleParser.basePath=base?base.href:url;
  5008. let eles=ruleParser.getPageElement(doc, iframe.contentWindow);
  5009. if(checkEval && !checkEval(doc)){
  5010. setTimeout(()=>{
  5011. checkIframe();
  5012. },waitTime);
  5013. return;
  5014. }else if(eles && eles.length>0){
  5015. callback(doc, eles);
  5016. }else if(tryTimes++ < 100){
  5017. setTimeout(()=>{
  5018. checkIframe();
  5019. },waitTime);
  5020. return;
  5021. }else{
  5022. if(failFromIframe++ > 2){
  5023. failFromIframe=0;
  5024. debug("Stop as failFromIframe");
  5025. isPause=true;
  5026. callback(false, false);
  5027. }else{
  5028. callback(false, false);
  5029. }
  5030. }
  5031. }catch(e){
  5032. debug("Stop as cors");
  5033. inCors=true;
  5034. if (forceState === 3) {
  5035. isPause=true;
  5036. }
  5037. if(!ruleParser.curSiteRule.pageElement){
  5038. ruleParser.curSiteRule.pageElement=allOfBody;
  5039. ruleParser.getInsert(true);
  5040. }
  5041. ruleParser.curSiteRule.action=0;
  5042. ruleParser.nextLinkHref=url;
  5043. callback(false, false);
  5044. nextPage();
  5045. }
  5046. document.body.removeChild(iframe);
  5047. }
  5048. setTimeout(()=>{
  5049. checkIframe();
  5050. },waitTime);
  5051. };
  5052. window.addEventListener('message', loadedHandler, false);
  5053. iframe.addEventListener('load', loadedHandler, false);
  5054. iframe.src=url;
  5055. document.body.appendChild(iframe);
  5056. }
  5057.  
  5058. var emuIframe,lastActiveUrl;
  5059. function emuPage(callback){
  5060. let orgPage=null,orgContent=null,preContent=null,iframeDoc,times=0,loadmoreBtn,pageEle,nextLink,loadmoreEnd=false,waitTimes=10,changed=false;
  5061. function returnFalse(log){
  5062. debug(log);
  5063. isPause=true;
  5064. callback(false, false);
  5065. if(emuIframe && emuIframe.parentNode){
  5066. emuIframe.parentNode.removeChild(emuIframe);
  5067. emuIframe=null;
  5068. }
  5069. }
  5070. async function checkPage(){
  5071. if(isPause)return loadPageOver();
  5072. try{
  5073. iframeDoc=emuIframe.contentDocument || emuIframe.contentWindow.document;
  5074. }catch(e){
  5075. returnFalse("Stop as cors");
  5076. return;
  5077. }
  5078.  
  5079. let waitTime=200,checkEval;
  5080. if(ruleParser.curSiteRule.waitElement){
  5081. checkEval = doc => {
  5082. return ruleParser.waitElement(doc);
  5083. };
  5084. }else if(ruleParser.curSiteRule.wait){
  5085. if(isNaN(ruleParser.curSiteRule.wait)){
  5086. try{
  5087. checkEval=(typeof _unsafeWindow.pagetualWait=='undefined') ? Function("doc", '"use strict";' + ruleParser.curSiteRule.wait) : _unsafeWindow.pagetualWait;
  5088. }catch(e){
  5089. debug(e);
  5090. }
  5091. }else{
  5092. waitTime=ruleParser.curSiteRule.wait;
  5093. }
  5094. }
  5095.  
  5096. if(!orgPage){
  5097. if(!loadmoreEnd){
  5098. loadmoreBtn=getLoadMore(iframeDoc);
  5099. if(loadmoreBtn && isVisible(loadmoreBtn, iframeDoc.defaultView)){
  5100. emuClick(loadmoreBtn);
  5101. let intv=setInterval(()=>{
  5102. loadmoreBtn=getLoadMore(iframeDoc);
  5103. if(!loadmoreBtn || !document.body.contains(loadmoreBtn) || !isVisible(loadmoreBtn, iframeDoc.defaultView)){
  5104. clearInterval(intv);
  5105. loadmoreEnd=true;
  5106. setTimeout(()=>{
  5107. checkPage();
  5108. },500);
  5109. }else if(isInViewPort(loadmoreBtn)){
  5110. emuClick(loadmoreBtn);
  5111. }
  5112. },200);
  5113. return;
  5114. }else{
  5115. loadmoreEnd=true;
  5116. }
  5117. }
  5118. if(checkEval && !checkEval(iframeDoc)){
  5119. waitTimes=10;
  5120. setTimeout(()=>{
  5121. checkPage();
  5122. },waitTime);
  5123. return;
  5124. }else {
  5125. nextLink = await ruleParser.getNextLink(iframeDoc);
  5126. pageEle = ruleParser.getPageElement(iframeDoc, iframeDoc.defaultView, true);
  5127. if (!pageEle || pageEle.length==0 || !nextLink) {
  5128. if (waitTimes-- > 0) {
  5129. setTimeout(() => {
  5130. checkPage();
  5131. }, waitTime);
  5132. return;
  5133. }
  5134. }
  5135. }
  5136. orgPage=pageEle;
  5137. if(!orgPage || orgPage.length==0){
  5138. returnFalse("Stop as no page when emu");
  5139. return;
  5140. }
  5141. if(orgPage[0].tagName=="UL")orgPage=orgPage[0].children;
  5142. if(nextLink){
  5143. orgPage=orgPage[parseInt(orgPage.length/2)];
  5144. if(orgPage.tagName=="IMG"){
  5145. if (!ruleParser.curSiteRule.lazyImgSrc) ruleParser.curSiteRule.lazyImgSrc = "0";
  5146. if (orgPage.src) {
  5147. orgContent = orgPage.src;
  5148. } else {
  5149. setTimeout(()=>{
  5150. checkPage();
  5151. },500);
  5152. return;
  5153. }
  5154. }else{
  5155. orgContent=orgPage.innerHTML;
  5156. }
  5157. preContent=orgContent;
  5158. if(!isVisible(nextLink, iframeDoc.defaultView)){
  5159. returnFalse("Stop as next hide when emu");
  5160. }else{
  5161. emuClick(nextLink);
  5162. setTimeout(()=>{
  5163. checkPage();
  5164. },500);
  5165. }
  5166. }else{
  5167. returnFalse("Stop as no next when emu");
  5168. }
  5169. return;
  5170. }
  5171. nextLink = nextLink || await ruleParser.getNextLink(iframeDoc);
  5172. if(!nextLink){
  5173. if(waitTimes-->0){
  5174. setTimeout(()=>{
  5175. checkPage();
  5176. },waitTime);
  5177. return;
  5178. }
  5179. }
  5180. if(times++ > 100){
  5181. returnFalse("Stop as timeout when emu");
  5182. return;
  5183. }
  5184. let eles=ruleParser.getPageElement(iframeDoc, iframeDoc.defaultView, true),checkItem;
  5185. if(eles && eles.length>0){
  5186. checkItem=eles;
  5187. if(eles[0].tagName=="UL")checkItem=eles[0].children;
  5188. checkItem=checkItem[parseInt(checkItem.length/2)];
  5189. }
  5190. if(!checkItem || (checkEval && !checkEval(iframeDoc))){
  5191. setTimeout(()=>{
  5192. checkPage();
  5193. },waitTime);
  5194. }else{
  5195. let checkInner;
  5196. if (checkItem.tagName == "IMG") {
  5197. if (checkItem.src) {
  5198. checkInner = checkItem.src;
  5199. } else {
  5200. setTimeout(() => {
  5201. checkPage();
  5202. }, waitTime);
  5203. return;
  5204. }
  5205. }else{
  5206. checkInner=checkItem.innerHTML;
  5207. }
  5208. if(orgPage!=checkItem || checkInner!=preContent){
  5209. changed=true;
  5210. orgPage=checkItem;
  5211. preContent=checkInner;
  5212. setTimeout(()=>{
  5213. checkPage();
  5214. },waitTime);
  5215. }else if(changed){
  5216. times = 0;
  5217. if (orgContent == preContent) {
  5218. returnFalse("Stop as same content");
  5219. } else {
  5220. callback(iframeDoc, eles);
  5221. }
  5222. }else{
  5223. if (times % 5 === 1) {
  5224. emuClick(nextLink);
  5225. }
  5226. setTimeout(()=>{
  5227. checkPage();
  5228. },waitTime);
  5229. }
  5230. }
  5231. }
  5232. if(!emuIframe){
  5233. let loaded=false;
  5234. emuIframe = document.createElement('iframe');
  5235. emuIframe.name = 'pagetual-iframe';
  5236. if(ruleParser.curSiteRule.sandbox!=false){
  5237. emuIframe.sandbox="allow-same-origin allow-scripts allow-popups allow-forms";
  5238. }
  5239. emuIframe.width = '100%';
  5240. emuIframe.height = '100';
  5241. emuIframe.frameBorder = '0';
  5242. emuIframe.style.cssText = 'margin:0!important;padding:0!important;flex:0;opacity:0!important;pointer-events:none!important;position:fixed;top:0px;left:0px;z-index:-2147483647;';
  5243. emuIframe.addEventListener("load", e => {
  5244. setTimeout(() => {
  5245. try {
  5246. iframeDoc = emuIframe.contentDocument || emuIframe.contentWindow.document;
  5247. } catch(e) {
  5248. returnFalse("Stop as cors");
  5249. return;
  5250. }
  5251. let code = ruleParser.curSiteRule.init;
  5252. if (code) {
  5253. try {
  5254. Function('doc','win','iframe','"use strict";' + code)(iframeDoc, iframeDoc.defaultView, emuIframe);
  5255. } catch(e) {
  5256. debug(e);
  5257. }
  5258. }
  5259. if (loaded) return;
  5260. loaded = true;
  5261. checkPage();
  5262. },500);
  5263. });
  5264. if (!lastActiveUrl) lastActiveUrl=location.href;
  5265. emuIframe.src = lastActiveUrl;
  5266. document.body.appendChild(emuIframe);
  5267. }else{
  5268. if (emuIframe.src != lastActiveUrl) emuIframe.src = lastActiveUrl;
  5269. checkPage();
  5270. }
  5271. }
  5272.  
  5273. var scrollToResizeInited = false;
  5274. var resizePool = [];
  5275. var scrollingToResize = false;
  5276.  
  5277. function scrollToResize(e) {
  5278. if (scrollingToResize) return;
  5279. else {
  5280. scrollingToResize = true;
  5281. let fitWidth = ruleParser.curSiteRule.fitWidth !== false;
  5282. let resizeHandler = () => {
  5283. resizePool.forEach(resizeArr => {
  5284. let iframe = resizeArr[1]();
  5285. let frameDoc = resizeArr[2]();
  5286. if(ruleParser.curSiteRule.singleUrl || forceState === 2){
  5287. iframe.style.height = (frameDoc.body.scrollHeight || frameDoc.body.offsetHeight) + "px";
  5288. iframe.style.minHeight = iframe.style.height;
  5289. iframe.style.width = "100%";
  5290. frameDoc.documentElement.scrollTop = 0;
  5291. frameDoc.documentElement.scrollLeft = 0;
  5292. }else{
  5293. let pageEle = resizeArr[0]();
  5294. if(pageEle){
  5295. let targetElement = pageEle[0];
  5296. if (!targetElement) return;
  5297. if(pageEle.length > 1){
  5298. targetElement = targetElement.parentNode;
  5299. }
  5300. let scrollHeight = targetElement.scrollHeight || targetElement.offsetHeight;
  5301. if(parseInt(iframe.style.height)==scrollHeight) return;
  5302. iframe.style.height=(scrollHeight+1)+"px";
  5303. let scrollTop = 0, scrollLeft = 0;
  5304. frameDoc.body.scrollTop = 0;
  5305. frameDoc.body.scrollLeft = 0;
  5306. while(targetElement && targetElement.offsetParent){
  5307. targetElement.offsetParent.scrollTop = targetElement.offsetTop;
  5308. if(targetElement.offsetParent.scrollTop == 0){
  5309. scrollTop += targetElement.offsetTop;
  5310. }
  5311. if(fitWidth){
  5312. targetElement.offsetParent.scrollLeft = targetElement.offsetLeft;
  5313. if(targetElement.offsetParent.scrollLeft == 0){
  5314. scrollLeft += targetElement.offsetLeft;
  5315. }
  5316. }
  5317. targetElement = targetElement.offsetParent;
  5318. }
  5319. frameDoc.documentElement.scrollTop = scrollTop;
  5320. frameDoc.documentElement.scrollLeft = scrollLeft;
  5321. if (frameDoc.documentElement.scrollTop == 0 && frameDoc.documentElement.scrollLeft == 0) {
  5322. frameDoc.body.scrollTop += scrollTop;
  5323. frameDoc.body.scrollLeft += scrollLeft;
  5324. }
  5325. if(!fitWidth && iframe.style.marginLeft == '0px'){
  5326. iframe.style.width = "100vw";
  5327. iframe.style.marginLeft = -iframe.getBoundingClientRect().left + "px";
  5328. }
  5329. }
  5330. }
  5331. });
  5332. };
  5333. setTimeout(() => {
  5334. scrollingToResize = false;
  5335. resizeHandler();
  5336. }, 200);
  5337. resizeHandler();
  5338. }
  5339. }
  5340.  
  5341. function forceIframe(url, callback){
  5342. url = url.indexOf('=') == -1 ? url.replace(/#[^#]*/,"") : url;
  5343. let curIframe = document.createElement('iframe'),iframeDoc,isloaded=false,inAction=true;
  5344. let loadedHandler = ()=>{
  5345. inAction=false;
  5346. if(isloaded)return;
  5347. isloaded=true;
  5348. ruleParser.insertPage(iframeDoc, [], url, null, true);
  5349. callback(curIframe, true);
  5350. let getIframe = () => {
  5351. return curIframe;
  5352. };
  5353. let getFrameDoc = () => {
  5354. return iframeDoc;
  5355. };
  5356. if(ruleParser.curSiteRule.singleUrl){
  5357. resizePool.push([() => {}, getIframe, getFrameDoc]);
  5358. }else{
  5359. let pageElement = ruleParser.getPageElement(iframeDoc,iframeDoc.defaultView);
  5360. let getPageEle = () => {
  5361. if (!pageElement || pageElement.length===0) {
  5362. pageElement = ruleParser.getPageElement(iframeDoc,iframeDoc.defaultView);
  5363. }
  5364. return pageElement;
  5365. };
  5366. resizePool.push([getPageEle, getIframe, getFrameDoc]);
  5367. }
  5368. scrollToResize();
  5369. };
  5370. curIframe.name = 'pagetual-iframe';
  5371. curIframe.sandbox="allow-same-origin allow-scripts allow-popups allow-forms";
  5372. curIframe.frameBorder = '0';
  5373. curIframe.scrolling="no";
  5374. curIframe.style.cssText = 'display: block; visibility: visible; float: none; clear: both; width: 100%; height: 0; background: initial; border: 0px; border-radius: 0px; margin: 0px; padding: 0px; z-index: 2147483647;';
  5375. curIframe.addEventListener("load", e=>{
  5376. try{
  5377. iframeDoc=curIframe.contentDocument || curIframe.contentWindow.document;
  5378. }catch(e){
  5379. debug("Stop as cors");
  5380. isPause=true;
  5381. callback(false, false);
  5382. return;
  5383. }
  5384. let css=ruleParser.curSiteRule.css || rulesData.customCss;
  5385. if(css){
  5386. css = css.replace(/^inIframe:/, "");
  5387. let styleEle=iframeDoc.createElement("style");
  5388. styleEle.innerHTML=css;
  5389. iframeDoc.head.appendChild(styleEle);
  5390. }
  5391. loadedHandler();
  5392. let code=ruleParser.curSiteRule.init;
  5393. if(code){
  5394. try{
  5395. Function('doc','win','iframe','"use strict";' + code)(iframeDoc,iframeDoc.defaultView,curIframe);
  5396. }catch(e){
  5397. debug(e);
  5398. }
  5399. }
  5400. });
  5401. let checkTimes=0,findPageEle=false;
  5402. let forceRefresh=e=>{
  5403. if(inAction || !iframeDoc)return;
  5404. inAction=true;
  5405. let foundNext=()=>{
  5406. document.removeEventListener("scroll", forceRefresh);
  5407. }
  5408. setTimeout(async () => {
  5409. inAction=false;
  5410. if(!ruleParser.nextLinkHref){
  5411. checkTimes++;
  5412. await ruleParser.getNextLink(iframeDoc);
  5413. if(ruleParser.nextLinkHref){
  5414. foundNext();
  5415. }else if(checkTimes>=10){
  5416. foundNext();
  5417. }else if(checkTimes>=3 && !findPageEle){
  5418. let pageElement = ruleParser.getPageElement(iframeDoc,iframeDoc.defaultView);
  5419. if(!pageElement){
  5420. inAction=true;
  5421. curIframe.contentWindow.location.reload();
  5422. }else{
  5423. findPageEle=true;
  5424. }
  5425. }
  5426. }else{
  5427. foundNext();
  5428. }
  5429. },50);
  5430. };
  5431. document.addEventListener("scroll", forceRefresh);
  5432. curIframe.src=url;
  5433. let insert=ruleParser.getInsert();
  5434. if(ruleParser.curSiteRule.singleUrl || forceState==2){
  5435. document.body.appendChild(loadingDiv);
  5436. document.body.appendChild(curIframe);
  5437. }else{
  5438. ruleParser.insertElement(curIframe);
  5439. }
  5440.  
  5441. if (!scrollToResizeInited) {
  5442. scrollToResizeInited = true;
  5443. document.addEventListener("scroll", scrollToResize);
  5444. }
  5445. return curIframe;
  5446. }
  5447.  
  5448. function loadPageOver(){
  5449. isLoading = false;
  5450. stopScroll = true;
  5451. setTimeout(() => {stopScroll = false}, 500);
  5452. if(loadingDiv.parentNode){
  5453. loadingDiv.parentNode.removeChild(loadingDiv);
  5454. }
  5455. }
  5456.  
  5457. var tryTimes = 0;
  5458.  
  5459. async function nextPage(){
  5460. if(typeof ruleParser.curSiteRule.manualMode=='undefined' ? rulesData.manualMode : ruleParser.curSiteRule.manualMode)return;
  5461. if(typeof ruleParser.curSiteRule.clickMode=='undefined' ? rulesData.clickMode : ruleParser.curSiteRule.clickMode)return;
  5462. if(isPause || isLoading || forceState==1)return;
  5463. if(ruleParser.curSiteRule.delay){
  5464. try{
  5465. let checkDelay=((typeof _unsafeWindow.pagetualDelay=='undefined') ? Function('"use strict";' + ruleParser.curSiteRule.delay) : _unsafeWindow.pagetualDelay)();
  5466. if(!checkDelay)return;
  5467. }catch(e){
  5468. debug(e);
  5469. }
  5470. }
  5471. if(ruleParser.curSiteRule.pageElementCss || ruleParser.curSiteRule.pageElementStyle || rulesData.pageElementCss){
  5472. ruleParser.getPageElement(document, _unsafeWindow);
  5473. }
  5474. let nextLink = ruleParser.nextLinkHref;
  5475. if (!nextLink) {
  5476. if (curPage == 1) {
  5477. await ruleParser.getNextLink(document);
  5478. nextLink = ruleParser.nextLinkHref;
  5479. }
  5480. if (!nextLink) {
  5481. isLoading = true;
  5482. if (curPage == 1 && (ruleParser.curSiteRule.pinUrl || tryTimes++ <= 10)) {
  5483. setTimeout(() => {isLoading = false}, 500);
  5484. }
  5485. return;
  5486. }
  5487. }
  5488. let pvGallery=document.querySelector("span.pv-gallery-container");
  5489. if(pvGallery && pvGallery.style.display!="none")return;
  5490. let insert=ruleParser.getInsert();
  5491. if (insert) {
  5492. if (curPage == 1) {
  5493. /*window.postMessage({
  5494. insert: geneSelector(ruleParser.curSiteRule.insertPos == 2 ? insert : insert.parentNode, true),
  5495. command: 'pagetual.insert'
  5496. }, '*');*/
  5497. }
  5498. let isJs = ruleParser.curSiteRule.action == 3 || /^(javascript|#)/.test(nextLink.replace(location.href,""));
  5499. if(!isJs){
  5500. emuIframe=null;
  5501. lastActiveUrl=nextLink;
  5502. if(location.protocol=="https:" && /^http:/.test(nextLink)){
  5503. nextLink=nextLink.replace(/^http/,"https");
  5504. }
  5505. }
  5506. isLoading=true;
  5507. ruleParser.insertElement(loadingDiv);
  5508. let parent=loadingDiv.parentNode;
  5509. if(parent.tagName=="TBODY"){
  5510. parent=parent.parentNode;
  5511. }
  5512. if(parent.tagName=="TABLE"){
  5513. parent.parentNode.appendChild(loadingDiv);
  5514. }
  5515. loadingDiv.style.cssText=loadingCSS;
  5516. let sleep=ruleParser.curSiteRule.sleep||0;
  5517. setTimeout(()=>{
  5518. if(ruleParser.curSiteRule.pageElementByJs){
  5519. var over=ele=>{
  5520. loadPageOver();
  5521. if (urlChanged || isPause) return;
  5522. if (ele) {
  5523. createPageBar(nextLink);
  5524. ruleParser.insertPage(null, ele, nextLink, null, true);
  5525. if(autoLoadNum>=0){
  5526. if(autoLoadNum!=0 && --autoLoadNum==0){
  5527. autoLoadNum=-1;
  5528. }else{
  5529. setTimeout(() => nextPage(), 1);
  5530. }
  5531. }
  5532. }else{
  5533. debug("Stop as no page when get by js");
  5534. isPause=true;
  5535. }
  5536. };
  5537. try{
  5538. ((typeof _unsafeWindow.pagetualPageElementByJs=='undefined') ? Function("over",'"use strict";' + ruleParser.curSiteRule.pageElementByJs) : _unsafeWindow.pagetualPageElementByJs)(over);
  5539. }catch(e){
  5540. debug(e);
  5541. }
  5542. }else if((forceState==2||ruleParser.curSiteRule.action==2) && !isJs){
  5543. forceIframe(nextLink, (iframe, eles)=>{
  5544. loadPageOver();
  5545. if (urlChanged || isPause) return;
  5546. let pageBar = createPageBar(nextLink);
  5547. if (pageBar) iframe.parentNode.insertBefore(pageBar, iframe);
  5548. if (autoLoadNum >= 0) {
  5549. if (autoLoadNum != 0 && --autoLoadNum == 0) {
  5550. autoLoadNum=-1;
  5551. } else {
  5552. setTimeout(() => nextPage(), 1);
  5553. }
  5554. }
  5555. });
  5556. }else if((forceState==3||ruleParser.curSiteRule.action==1) && !isJs){
  5557. requestFromIframe(nextLink, (doc, eles)=>{
  5558. loadPageOver();
  5559. if (urlChanged || isPause) return;
  5560. if (eles) {
  5561. ruleParser.insertPage(doc, eles, nextLink, ()=>{
  5562. createPageBar(nextLink);
  5563. }, true);
  5564. if(autoLoadNum>=0){
  5565. if(autoLoadNum!=0 && --autoLoadNum==0){
  5566. autoLoadNum=-1;
  5567. }else{
  5568. setTimeout(() => nextPage(), 1);
  5569. }
  5570. }
  5571. }
  5572. });
  5573. }else{
  5574. if(!isJs){
  5575. requestDoc(nextLink, (eles)=>{
  5576. loadPageOver();
  5577. if (urlChanged || isPause) return;
  5578. if (eles) {
  5579. createPageBar(nextLink);
  5580. if(autoLoadNum>=0){
  5581. if(autoLoadNum!=0 && --autoLoadNum==0){
  5582. autoLoadNum=-1;
  5583. }else{
  5584. setTimeout(() => nextPage(), 1);
  5585. }
  5586. }
  5587. }
  5588. });
  5589. }else{
  5590. emuPage((doc, eles)=>{
  5591. loadPageOver();
  5592. if (urlChanged || isPause) return;
  5593. if (eles) {
  5594. ruleParser.insertPage(doc, eles, "", ()=>{
  5595. createPageBar(nextLink);
  5596. }, true);
  5597. if(autoLoadNum>=0){
  5598. if(autoLoadNum!=0 && --autoLoadNum==0){
  5599. autoLoadNum=-1;
  5600. }else{
  5601. setTimeout(() => nextPage(), 1);
  5602. }
  5603. }
  5604. }
  5605. });
  5606. }
  5607. }
  5608. },sleep);
  5609. }
  5610. }
  5611.  
  5612. function init(){
  5613. initRules(()=>{
  5614. initPage();
  5615. });
  5616. }
  5617.  
  5618. function visibilitychangeHandler(){
  5619. document.removeEventListener('visibilitychange', visibilitychangeHandler);
  5620. init();
  5621. }
  5622.  
  5623. setTimeout(()=>{
  5624. if (document.hidden) {
  5625. document.addEventListener('visibilitychange', visibilitychangeHandler);
  5626. } else {
  5627. init();
  5628. }
  5629. },100);
  5630. })();