东方永页机

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

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

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

QingJ © 2025

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