东方永页机

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

当前为 2023-01-28 提交的版本,查看 最新版本

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

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址