东方永页机

自动翻页 - 加载并拼接下一分页内容至当前页尾,无需规则自动适配任意网页

当前为 2022-10-11 提交的版本,查看 最新版本

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