东方永页机

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

当前为 2022-12-09 提交的版本,查看 最新版本

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

QingJ © 2025

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