东方永页机

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

目前为 2022-11-29 提交的版本。查看 最新版本

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