东方永页机

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

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

  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.5
  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)\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>.title {
  2532. margin: -5px 45px 10px 45px;
  2533. font-size: 20px;
  2534. font-weight: bold;
  2535. cursor: move;
  2536. border-bottom: 1px solid black;
  2537. user-select: none;
  2538. color: orangered;
  2539. font-family: Times New Roman;
  2540. }
  2541. #pagetual-picker button {
  2542. background: none;
  2543. border: none;
  2544. vertical-align: top;
  2545. transition: transform .15s ease-in-out;
  2546. float: right;
  2547. cursor: pointer;
  2548. }
  2549. #pagetual-picker button:hover {
  2550. transform: scale(1.2);
  2551. }
  2552. #pagetual-picker>.closePicker {
  2553. position: absolute;
  2554. top: 3px;
  2555. right: 10px;
  2556. }
  2557. #pagetual-picker>.logoToHome {
  2558. position: absolute;
  2559. top: 3px;
  2560. left: 10px;
  2561. }
  2562. #pagetual-picker .selector{
  2563. display: inline-block;
  2564. width: 290px;
  2565. height: 20px;
  2566. max-width: calc(65vw - 50px);
  2567. padding: 6px 12px;
  2568. font-size: 16px;
  2569. font-weight: 400;
  2570. line-height: 1.5;
  2571. color: #495057;
  2572. background-color: #fff;
  2573. background-clip: padding-box;
  2574. border: 1px solid #ced4da;
  2575. border-radius: 4px;
  2576. transition: border-color .15s ease-in-out,box-shadow .15s ease-in-out;
  2577. box-sizing: content-box;
  2578. }
  2579. #pagetual-picker .selector:focus {
  2580. color: #495057;
  2581. background-color: #fff;
  2582. border-color: #80bdff;
  2583. outline: 0;
  2584. box-shadow: 0 0 0 3.2px rgb(0 123 255 / 25%);
  2585. }
  2586. #pagetual-picker [type=checkbox],
  2587. #pagetual-picker [type=radio] {
  2588. line-height: 20px;
  2589. height: 25px;
  2590. width: 25px;
  2591. margin-left: 5px;
  2592. vertical-align: middle;
  2593. appearance: auto;
  2594. display: inline-block;
  2595. }
  2596. #pagetual-picker label {
  2597. font-size: 18px;
  2598. line-height: 25px;
  2599. vertical-align: middle;
  2600. display: inline-block;
  2601. color: black;
  2602. }
  2603. #pagetual-picker .bottom {
  2604. text-align: left;
  2605. margin: 10px 0;
  2606. width: 100%;
  2607. }
  2608. #pagetual-picker .bottom>button {
  2609. float: right;
  2610. }
  2611. #pagetual-picker svg {
  2612. width: 30px;
  2613. height: 30px;
  2614. vertical-align: middle;
  2615. fill: #161616;
  2616. overflow: hidden;
  2617. }
  2618. #pagetual-picker .allpath {
  2619. font-size: 18px;
  2620. margin: 10px;
  2621. max-width: 350px;
  2622. word-break: break-all;
  2623. cursor: context-menu;
  2624. overflow: hidden;
  2625. max-height: 42px;
  2626. -moz-transition:max-height 1s ease-in;
  2627. -webkit-transition:max-height 1s ease-in;
  2628. transition:max-height 1s ease-in;
  2629. color: black;
  2630. }
  2631. #pagetual-picker .allpath:hover {
  2632. max-height: calc(100vh - 130px);
  2633. overflow: auto;
  2634. }
  2635. #pagetual-picker .allpath>span.path {
  2636. cursor: pointer;
  2637. }
  2638. #pagetual-picker .allpath>span.path:hover {
  2639. color: orangered;
  2640. }
  2641. #pagetual-picker .moreConfig {
  2642. display: flex;
  2643. justify-content: space-between;
  2644. border-top: 1px solid;
  2645. padding-top: 10px;
  2646. width: 100%;
  2647. }
  2648. #pagetual-picker .command {
  2649. width: 100%;
  2650. color: black;
  2651. text-align: center;
  2652. font-size: large;
  2653. margin-top: 10px;
  2654. }
  2655. #pagetual-picker .command:hover {
  2656. color: orangered;
  2657. }
  2658. `;
  2659. _GM_addStyle(cssText);
  2660. this.mainSignDiv = this.createSignDiv();
  2661. this.allSignDiv = [];
  2662. let frame = document.createElement("div");
  2663. frame.id = "pagetual-picker";
  2664. frame.innerHTML = createHTML(`
  2665. <button title="Pagetual" type="button" class="logoToHome">
  2666. <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>
  2667. </button>
  2668. <div class="title">${i18n("picker")}</div>
  2669. <button title="${i18n("closePicker")}" type="button" class="closePicker">
  2670. <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>
  2671. </button>
  2672. <div class="allpath" title="${i18n("switchSelector")}"></div>
  2673. <div>
  2674. <textarea class="selector" spellcheck="false" name="selector" placeholder="${i18n("pickerPlaceholder")}"></textarea>
  2675. <button id="check" title="${i18n("pickerCheck")}" type="button">
  2676. <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>
  2677. </button>
  2678. </div>
  2679. <div class="bottom">
  2680. <input name="xpath" id="checkbox_id" type="checkbox">
  2681. <label for="checkbox_id">XPath</label>
  2682. <button id="edit" title="${i18n("gotoEdit")}" type="button">
  2683. <svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" style="color: orangered;fill: orangered;">
  2684. <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">
  2685. </path>
  2686. </svg>
  2687. </button>
  2688. </div>
  2689. <div class="moreConfig">
  2690. <div title="${i18n('forceStateIframe')}">
  2691. <input name="forceState" id="forceStateIframe" type="radio">
  2692. <label for="forceStateIframe">Iframe</label>
  2693. </div>
  2694. <div title="${i18n('forceStateDynamic')}">
  2695. <input name="forceState" id="forceStateDynamic" type="radio">
  2696. <label for="forceStateDynamic">Dynamic</label>
  2697. </div>
  2698. <div title="${i18n('forceStateDisable')}">
  2699. <input name="forceState" id="forceStateDisable" type="radio">
  2700. <label for="forceStateDisable">Disable</label>
  2701. </div>
  2702. </div>
  2703. <button id="nextSwitch" class="command" title="${i18n("nextSwitch")}" type="button">${i18n("nextSwitch")}</button>
  2704. <button id="loadNow" class="command" title="${i18n("loadNow")}" type="button">${i18n("loadNow")}</button>
  2705. `);
  2706. let forceStateIframe = frame.querySelector("#forceStateIframe");//forceState 1 禁用 2 强嵌 3 动态
  2707. let forceStateDynamic = frame.querySelector("#forceStateDynamic");
  2708. let forceStateDisable = frame.querySelector("#forceStateDisable");
  2709. let clickRadio = e => {
  2710. let radio = e.currentTarget.querySelector('input');
  2711. if (radio.checked) {
  2712. forceState = "";
  2713. } else {
  2714. switch (radio.id) {
  2715. case "forceStateIframe":
  2716. forceState = 2;
  2717. break;
  2718. case "forceStateDynamic":
  2719. forceState = 3;
  2720. break;
  2721. case "forceStateDisable":
  2722. forceState = 1;
  2723. break;
  2724. default:
  2725. return;
  2726. }
  2727. }
  2728. storage.setItem("forceState_"+location.host, forceState);
  2729. self.close();
  2730. location.reload();
  2731. };
  2732. forceStateIframe.parentNode.addEventListener("mousedown", clickRadio);
  2733. forceStateDynamic.parentNode.addEventListener("mousedown", clickRadio);
  2734. forceStateDisable.parentNode.addEventListener("mousedown", clickRadio);
  2735. if (forceState == 1) forceStateDisable.checked = true;
  2736. else if (forceState == 2) forceStateIframe.checked = true;
  2737. else if (forceState == 3) forceStateDynamic.checked = true;
  2738. let closeBtn = frame.querySelector(".closePicker");
  2739. let homeBtn = frame.querySelector(".logoToHome");
  2740. let title = frame.querySelector(".title");
  2741. let allpath = frame.querySelector(".allpath");
  2742. let selectorInput = frame.querySelector(".selector");
  2743. let xpath = frame.querySelector("#checkbox_id");
  2744. let checkBtn = frame.querySelector("#check");
  2745. let editBtn = frame.querySelector("#edit");
  2746. let nextSwitch = frame.querySelector("#nextSwitch");
  2747. let loadNow = frame.querySelector("#loadNow");
  2748. nextSwitch.addEventListener("click", e => {
  2749. self.close();
  2750. NextSwitch.getInstance().start();
  2751. }, true);
  2752. loadNow.addEventListener("click", e => {
  2753. self.close();
  2754. let loadNum=window.prompt(i18n("loadConfirm"), "1");
  2755. if(loadNum==="" || loadNum===null)return;
  2756. autoLoadNum=Math.abs(parseInt(loadNum));
  2757. nextPage();
  2758. }, true);
  2759. closeBtn.addEventListener("click", e => {
  2760. self.close();
  2761. }, true);
  2762. homeBtn.addEventListener("click", e => {
  2763. _GM_openInTab(configPage[0], {active: true});
  2764. }, true);
  2765. let moving = false;
  2766. let moveHanlder = e => {
  2767. frame.style.left = e.clientX - 200 + "px";
  2768. frame.style.top = e.clientY - 15 + "px";
  2769. e.stopPropagation();
  2770. e.preventDefault();
  2771. };
  2772. let upHanlder = e => {
  2773. moving = false;
  2774. document.removeEventListener("mousemove", moveHanlder, true);
  2775. title.removeEventListener("mouseup", upHanlder, true);
  2776. e.stopPropagation();
  2777. e.preventDefault();
  2778. };
  2779. title.addEventListener("mousedown", e => {
  2780. moving = true;
  2781. document.addEventListener("mousemove", moveHanlder, true);
  2782. title.addEventListener("mouseup", upHanlder, true);
  2783. });
  2784. frame.addEventListener("mouseenter", e => {
  2785. if (moving) return;
  2786. if (self.mainSignDiv.parentNode) self.mainSignDiv.parentNode.removeChild(self.mainSignDiv);
  2787. self.checkInputSelector();
  2788. });
  2789. frame.addEventListener("mouseleave", e => {
  2790. if (moving) return;
  2791. document.body.appendChild(self.mainSignDiv);
  2792. self.clearSigns();
  2793. });
  2794. checkBtn.addEventListener("click", e => {
  2795. self.checkInputSelector();
  2796. if (this.selectorInput.value) _GM_setClipboard(this.selectorInput.value);
  2797. });
  2798. xpath.addEventListener("click", e => {
  2799. if (!selectorInput.value) {
  2800. self.setSelectorDiv("");
  2801. return;
  2802. }
  2803. let element = getElement(selectorInput.value, document);
  2804. let selector = self.getSelectorFromEle(element);
  2805. self.setSelectorDiv(selector);
  2806. selectorInput.value = selector;
  2807. });
  2808. editBtn.addEventListener("click", e => {
  2809. let editTemp;
  2810. if (ruleParser.curSiteRule.url && !ruleParser.curSiteRule.singleUrl) {
  2811. editTemp = ruleParser.curSiteRule;
  2812. } else {
  2813. editTemp = {
  2814. name: document.title,
  2815. url: "^" + location.origin.replace(/^https?/, "https?").replace(/\./g,"\\.") + "/"
  2816. };
  2817. }
  2818. if (selectorInput.value) {
  2819. editTemp.pageElement = selectorInput.value;
  2820. }
  2821. delete editTemp.from;
  2822. delete editTemp.type;
  2823. delete editTemp.updatedAt;
  2824. rulesData.editTemp = editTemp;
  2825. storage.setItem("rulesData", rulesData);
  2826. _GM_openInTab(configPage[0], {active: true});
  2827. });
  2828. this.frame = frame;
  2829. this.xpath = xpath;
  2830. this.allpath = allpath;
  2831. this.selectorInput = selectorInput;
  2832. this.nextSwitch = nextSwitch;
  2833. this.loadNow = loadNow;
  2834. this.moveHandler = e => {
  2835. if (e.target === document) return;
  2836. self.adjustSignDiv(self.mainSignDiv, self.getTarget(e.target));
  2837. };
  2838. this.clickHandler = e => {
  2839. if (self.inPicker) {
  2840. e.stopPropagation();
  2841. e.preventDefault();
  2842. }
  2843. let target = self.getTarget(e.target);
  2844. let selector = self.getSelectorFromEle(target);
  2845. self.setSelectorDiv(selector);
  2846. selectorInput.value = selector;
  2847. };
  2848. }
  2849.  
  2850. getTarget(ele) {
  2851. while (ele.parentNode && (ele.scrollWidth === 0 || ele.scrollHeight === 0)) {
  2852. ele = ele.parentNode;
  2853. }
  2854. return ele;
  2855. }
  2856.  
  2857. close() {
  2858. this.clearSigns();
  2859. if (this.frame.parentNode) this.frame.parentNode.removeChild(this.frame);
  2860. if (this.mainSignDiv.parentNode) this.mainSignDiv.parentNode.removeChild(this.mainSignDiv);
  2861. document.body.classList.remove("pagetual-picker");
  2862. document.body.removeEventListener("mousemove", this.moveHandler, true);
  2863. document.body.removeEventListener("click", this.clickHandler, true);
  2864. this.inPicker = false;
  2865. }
  2866.  
  2867. setImportant(ele, prop, value) {
  2868. ele.style.setProperty(prop, value, "important");
  2869. }
  2870.  
  2871. createSignDiv() {
  2872. let signDiv = document.createElement("div");
  2873. this.setImportant(signDiv, "position", "absolute");
  2874. this.setImportant(signDiv, "pointer-events", "none");
  2875. this.setImportant(signDiv, "z-index", "2147483647");
  2876. this.setImportant(signDiv, "background", "rgba(120, 170, 210, 0.6)");
  2877. this.setImportant(signDiv, "transition", "all 0.15s ease-out");
  2878. this.setImportant(signDiv, "box-shadow", "rgb(0 0 0) 0px 0px 3px 0px");
  2879. return signDiv;
  2880. }
  2881.  
  2882. adjustSignDiv(div, target) {
  2883. let rect = target.getBoundingClientRect();
  2884. this.setImportant(div, "width", rect.width + "px");
  2885. this.setImportant(div, "height", rect.height + "px");
  2886. this.setImportant(div, "left", rect.left + window.scrollX + "px");
  2887. this.setImportant(div, "top", rect.top + window.scrollY + "px");
  2888. }
  2889.  
  2890. getSelectorFromEle(ele) {
  2891. return this.xpath.checked ? createXPathFromElement(ele) : geneSelector(ele, true);
  2892. }
  2893.  
  2894. setSelectorDiv(selector) {
  2895. let self = this;
  2896. this.allpath.innerHTML = createHTML("");
  2897. if (!selector) return;
  2898. if (this.xpath.checked) {
  2899. let span = document.createElement("span");
  2900. span.innerText = selector;
  2901. span.addEventListener("click", e => {
  2902. self.selectorInput.value = selector;
  2903. self.checkInputSelector();
  2904. }, true);
  2905. this.allpath.appendChild(span);
  2906. } else {
  2907. selector.split(">").forEach((item, index) => self.geneSelectorItem(item, index));
  2908. }
  2909. }
  2910.  
  2911. geneSelectorItem(item, index) {
  2912. let self = this;
  2913. item = item.trim();
  2914. if (!item) return;
  2915. if (index !== 0) {
  2916. let span = document.createElement("span");
  2917. span.innerText = " > ";
  2918. this.allpath.appendChild(span);
  2919. }
  2920. let span = document.createElement("span");
  2921. span.className = "path";
  2922. span.innerText = item;
  2923. span.addEventListener("click", e => {
  2924. let selector = "";
  2925. let target = e.target;
  2926. while (target) {
  2927. selector = target.innerText + selector;
  2928. target = target.previousElementSibling;
  2929. }
  2930. self.selectorInput.value = selector;
  2931. self.checkInputSelector();
  2932. }, true);
  2933. this.allpath.appendChild(span);
  2934. }
  2935.  
  2936. checkInputSelector() {
  2937. let self = this;
  2938. this.clearSigns();
  2939. if (!this.selectorInput.value) return;
  2940. let eles = getAllElements(this.selectorInput.value, document);
  2941. if (eles && eles.length > 0) {
  2942. eles.forEach(ele => {
  2943. let sign = self.createSignDiv();
  2944. document.body.appendChild(sign);
  2945. self.adjustSignDiv(sign, ele);
  2946. self.signList.push(sign);
  2947. });
  2948. }
  2949. }
  2950.  
  2951. clearSigns() {
  2952. this.signList.forEach(sign => {
  2953. if (sign.parentNode) sign.parentNode.removeChild(sign);
  2954. });
  2955. this.signList = [];
  2956. }
  2957.  
  2958. start() {
  2959. if (this.inPicker) return;
  2960. this.inPicker = true;
  2961. document.documentElement.appendChild(this.frame);
  2962. document.body.appendChild(this.mainSignDiv);
  2963. document.body.classList.add("pagetual-picker");
  2964.  
  2965. document.body.addEventListener("mousemove", this.moveHandler, true);
  2966. document.body.addEventListener("click", this.clickHandler, true);
  2967. this.xpath.checked = isXPath(ruleParser.curSiteRule.pageElement);
  2968.  
  2969. this.loadNow.style.display = ruleParser.nextLinkHref ? "block" : "none";
  2970. if (ruleParser.curSiteRule.nextLink && Array && Array.isArray && Array.isArray(ruleParser.curSiteRule.nextLink)) {
  2971. this.nextSwitch.style.display = "block";
  2972. } else {
  2973. this.nextSwitch.style.display = "none";
  2974. }
  2975.  
  2976. let pageElementSel=ruleParser.curSiteRule.pageElement || "";
  2977. if(Array && Array.isArray && Array.isArray(pageElementSel)){
  2978. pageElementSel=pageElementSel[nextIndex<pageElementSel.length?nextIndex:0];
  2979. }
  2980. this.setSelectorDiv(pageElementSel);
  2981. }
  2982. }
  2983.  
  2984. function initConfig(){
  2985. initView();
  2986. try{
  2987. if(_unsafeWindow.initedPagetual){
  2988. if(ruleImportUrlReg.test(location.href)){
  2989. showTips(i18n('duplicate'));
  2990. }
  2991. return true;
  2992. }
  2993. _unsafeWindow.initedPagetual=true;
  2994. }catch(e){}
  2995. _GM_registerMenuCommand(i18n(forceState==1?"enable":"disableSite"), ()=>{
  2996. forceState=(forceState==1?0:1);
  2997. storage.setItem("forceState_"+location.host, forceState);
  2998. showTips(i18n(forceState==1?"disableSiteTips":"enableSiteTips"));
  2999. if(!ruleParser.curSiteRule.url) location.reload();
  3000. });
  3001. _GM_registerMenuCommand(i18n("update"), ()=>{
  3002. updateRules(()=>{
  3003. showTips(i18n("updateSucc"));
  3004. location.reload();
  3005. },(rule,err)=>{
  3006. showTips("Update "+rule.url+" rules fail!");
  3007. });
  3008. showTips(i18n("beginUpdate"));
  3009. });
  3010. if(guidePage.test(location.href)){
  3011. function createEdit(){
  3012. var options = {
  3013. mode: 'code',
  3014. modes: ['code', 'tree'],
  3015. templates: [
  3016. {
  3017. text: 'New site',
  3018. title: 'Insert a new site',
  3019. className: 'jsoneditor-type-object',
  3020. field: 'SiteTemplate',
  3021. value: {
  3022. 'name': 'Site name',
  3023. 'url': 'Site url'
  3024. }
  3025. }
  3026. ],
  3027. schema: {
  3028. "title": "Sites data",
  3029. "description": "Object containing site config",
  3030. "type": "array",
  3031. "items": {
  3032. "type": 'object',
  3033. "properties": {
  3034. "name": {
  3035. "title": "Site Name",
  3036. "description": "The site's name.",
  3037. "examples": [
  3038. "Google"
  3039. ],
  3040. "type": "string"
  3041. },
  3042. "url": {
  3043. "title": "Site Url",
  3044. "description": "The Regexp of site's url.",
  3045. "examples": [
  3046. "^https:\/\/yande\\.re\/"
  3047. ],
  3048. "type": "string"
  3049. }
  3050. },
  3051. "required": ["name", "url"]
  3052. }
  3053. }
  3054. };
  3055. var container = document.getElementById("jsoneditor");
  3056. container.style.height='800px';
  3057. var editor = new JSONEditor(container, options);
  3058. editor.set(ruleParser.customRules);
  3059. document.querySelector("#saveBtn").onclick=e=>{
  3060. try{
  3061. storage.setItem("hpRules", []);
  3062. storage.setItem("smartRules", []);
  3063. let customRules=editor.get();
  3064. if(!customRules){
  3065. storage.setItem("customRules", "");
  3066. }else{
  3067. if(Array && Array.isArray && !Array.isArray(customRules)){
  3068. showTips("Rules must be a Array!");
  3069. return;
  3070. }
  3071. debug(customRules);
  3072. storage.setItem("customRules", customRules);
  3073. }
  3074. }catch(e){
  3075. debug(e);
  3076. showTips("JSON error, check again!");
  3077. return;
  3078. }
  3079. showTips("Edit successfully");
  3080. };
  3081. }
  3082. if(JSONEditor){
  3083. createEdit();
  3084. }else{
  3085. window.onload = e => {
  3086. createEdit();
  3087. }
  3088. }
  3089. return true;
  3090. }
  3091. if(location.href.indexOf("PagetualGuide")!=-1) return true;
  3092.  
  3093. var configCon,insertPos;
  3094. var noRules=!rulesData.urls || rulesData.urls.length===0;
  3095.  
  3096. let inConfig = false;
  3097. for (let i = 0; i < configPage.length; i++) {
  3098. if (configPage[i] == location.href) {
  3099. inConfig = true;
  3100. break;
  3101. }
  3102. }
  3103. if(ruleImportUrlReg.test(location.href) || inConfig){
  3104. let importing = false;
  3105. if(noRules){
  3106. setTimeout(() => {
  3107. if (!importing) showTips(i18n("firstAlert"));
  3108. }, 3000);
  3109. setTimeout(() => {
  3110. if (!importing) showTips(i18n("firstAlert"));
  3111. }, 6000);
  3112. showTips(i18n("firstAlert"));
  3113. }
  3114. let createImportBtn = () => {
  3115. let importBtn = document.createElement("button");
  3116. importBtn.innerText = i18n("import");
  3117. importBtn.style.marginTop = "100px";
  3118. importBtn.style.float = "right";
  3119. importBtn.style.position = "relative";
  3120. importBtn.style.display = "block";
  3121. importBtn.style.fontSize = "20px";
  3122. importBtn.addEventListener("click", e => {
  3123. let parentNode = importBtn.parentNode;
  3124. if (!parentNode) return;
  3125. parentNode.removeChild(importBtn);
  3126. try {
  3127. let rules=parentNode.innerText.trim();
  3128. let isContent=/['"]name['"]/i.test(rules);
  3129. if(isContent){
  3130. let ruleList=JSON.parse(`[${rules}]`);
  3131. for(let i in ruleList){
  3132. let hasRule = false;
  3133. let r = ruleList[i];
  3134. for(let j in ruleParser.customRules){
  3135. if(ruleParser.customRules[j].name == r.name){
  3136. ruleParser.customRules[j] = r;
  3137. hasRule = true;
  3138. break;
  3139. }
  3140. }
  3141. if(!hasRule)ruleParser.customRules.push(r);
  3142. }
  3143. storage.setItem("customRules", ruleParser.customRules);
  3144. storage.setItem("hpRules", []);
  3145. storage.setItem("smartRules", []);
  3146. showTips(i18n("importSucc"));
  3147. }else{
  3148. rules=rules.split("\n");
  3149. let diff=false;
  3150. for(let c=0;c<rules.length;c++){
  3151. let urlArr=rules[c].split("|"),url,type=1;
  3152. if(urlArr.length==1){
  3153. url=urlArr[0].trim();
  3154. if(!/^http/.test(url)){
  3155. showTips("Wrong url, check again!");
  3156. return;
  3157. }
  3158. }else if(urlArr.length==2){
  3159. type=urlArr[0].trim();
  3160. url=urlArr[1].trim();
  3161. if(!/^http/.test(url)){
  3162. showTips("Wrong url, check again!");
  3163. return;
  3164. }
  3165. }else{
  3166. break;
  3167. }
  3168. let maxId=0,hasUrl=false;
  3169. if(!rulesData.urls){
  3170. rulesData.urls=[];
  3171. maxId=1;
  3172. }else{
  3173. rulesData.urls.forEach(u=>{
  3174. if(maxId<u.id){
  3175. maxId=u.id;
  3176. }
  3177. if(u.url==url){
  3178. hasUrl=true;
  3179. }
  3180. });
  3181. if(hasUrl)break;
  3182. }
  3183. diff=true;
  3184. if(!rulesData.sort)rulesData.sort=[1];
  3185. rulesData.urls.push({id:maxId+1,url:url,type:type});
  3186. rulesData.sort.unshift(maxId+1);
  3187. }
  3188. if(!diff){
  3189. showTips("Already exists!");
  3190. return;
  3191. }
  3192. storage.setItem("rulesData", rulesData);
  3193.  
  3194. if(rulesData.urls)ruleUrls=ruleUrls.concat(rulesData.urls);
  3195. if(rulesData.sort){
  3196. let urls=[];
  3197. rulesData.sort.forEach(id=>{
  3198. for(let s=0;s<ruleUrls.length;s++){
  3199. if(id==ruleUrls[s].id){
  3200. urls.push(ruleUrls[s]);
  3201. break;
  3202. }
  3203. }
  3204. });
  3205. ruleUrls=urls;
  3206. }
  3207. updateRules(()=>{
  3208. showTips(i18n("updateSucc"));
  3209. location.reload();
  3210. },(rule,err)=>{
  3211. showTips("Update "+rule.url+" rules fail!");
  3212. });
  3213. importing = true;
  3214. showTips(i18n("beginUpdate"));
  3215. }
  3216. } catch (e) {
  3217. _GM_notification(e.toString());
  3218. }
  3219. });
  3220. return importBtn;
  3221. };
  3222. [].forEach.call(document.querySelectorAll('pre[name=pagetual],pre[name=user-content-pagetual]'), pre => {
  3223. let importBtn = createImportBtn();
  3224. let clientHeight = 35 - pre.clientHeight;
  3225. if (clientHeight > -20) clientHeight = -20;
  3226. importBtn.style.marginTop = `${clientHeight}px`;
  3227. pre.appendChild(importBtn);
  3228. });
  3229. document.addEventListener("mouseover", e => {
  3230. if (e.target.tagName === "PRE") {
  3231. let nameAttr=e.target.getAttribute("name");
  3232. if(nameAttr=="pagetual" || nameAttr=="user-content-pagetual"){
  3233. if (e.target.querySelector('button')) return;
  3234. let importBtn = createImportBtn();
  3235. let clientHeight = 35 - e.target.clientHeight;
  3236. if (clientHeight > -20) clientHeight = -20;
  3237. importBtn.style.marginTop = `${clientHeight}px`;
  3238. e.target.appendChild(importBtn);
  3239. }
  3240. }
  3241. });
  3242.  
  3243. if(inConfig){
  3244. _GM_addStyle(`
  3245. p>span:nth-child(1),p>span:nth-child(2),p>span:nth-child(3){
  3246. cursor: pointer;
  3247. user-select: none;
  3248. }
  3249. p>span:nth-child(1):hover,p>span:nth-child(2):hover,p>span:nth-child(3):hover{
  3250. color:red;
  3251. }
  3252. .updateDate{
  3253. cursor: pointer;
  3254. user-select: none;
  3255. }
  3256. .updateDate:hover{
  3257. color:red;
  3258. }
  3259. input[type=number]::-webkit-inner-spin-button,
  3260. input[type=number]::-webkit-outer-spin-button {
  3261. -webkit-appearance: none;
  3262. margin: 0;
  3263. }
  3264. input[type=number] {
  3265. -moz-appearance:textfield;
  3266. }
  3267. `);
  3268. document.querySelector("[name='user-content-click2import'],[name='click2import']").innerText=i18n("click2ImportRule")
  3269. configCon=document.querySelector(".markdown-body");
  3270. insertPos=configCon.querySelector("hr");
  3271.  
  3272. if(!noRules){
  3273. document.querySelector("pre[name='user-content-pagetual'],pre[name='pagetual']").style.display="none";
  3274. document.querySelector("p[name='user-content-click2import'],p[name='click2import']").style.display="none";
  3275. }
  3276. }else return true;
  3277. }else return false;
  3278. class Rulebar {
  3279. init(ruleUrl){
  3280. this.ruleUrl=ruleUrl;
  3281. this.item=document.createElement("p");
  3282. this.item.dataset.id=this.ruleUrl.id;
  3283. let url=document.createElement("span");
  3284. url.innerHTML=ruleUrl.url;
  3285. let up=document.createElement("span");
  3286. up.innerHTML="↑ ";
  3287. up.title=i18n("sortTitle");
  3288. let down=document.createElement("span");
  3289. down.innerHTML="↓ ";
  3290. down.title=i18n("sortTitle");
  3291. let del=document.createElement("span");
  3292. del.innerHTML="× ";
  3293. up.onclick=e=>{
  3294. this.moveUp();
  3295. };
  3296. down.onclick=e=>{
  3297. this.moveDown();
  3298. };
  3299. del.onclick=e=>{
  3300. this.del();
  3301. };
  3302. this.item.appendChild(up);
  3303. this.item.appendChild(down);
  3304. this.item.appendChild(del);
  3305. this.item.appendChild(url);
  3306. configCon.insertBefore(this.item, insertPos);
  3307. }
  3308. saveSort(){
  3309. let sort=[];
  3310. [].forEach.call(this.item.parentNode.querySelectorAll("p[data-id]"), i=>{
  3311. sort.push(i.dataset.id);
  3312. });
  3313. rulesData.sort=sort;
  3314. storage.setItem("rulesData", rulesData);
  3315. }
  3316. moveUp(){
  3317. let preE=this.item.previousElementSibling;
  3318. if(preE.tagName=="P" && preE.children.length>1){
  3319. this.item.parentNode.insertBefore(this.item,preE);
  3320. this.saveSort();
  3321. }
  3322. }
  3323. moveDown(){
  3324. let nextE=this.item.nextElementSibling;
  3325. if(nextE.tagName=="P" && nextE.children.length>1){
  3326. this.item.parentNode.insertBefore(nextE,this.item);
  3327. this.saveSort();
  3328. }
  3329. }
  3330. del(){
  3331. if(this.ruleUrl.id<2){
  3332. showTips(i18n("cantDel"));
  3333. }else if(window.confirm(i18n("confirmDel"))){
  3334. for(let u=0;u<rulesData.urls.length;u++){
  3335. if(this.ruleUrl.id==rulesData.urls[u].id){
  3336. rulesData.urls.splice(u,1);
  3337. break;
  3338. }
  3339. }
  3340. for(let u=0;u<ruleUrls.length;u++){
  3341. if(this.ruleUrl.id==ruleUrls[u].id){
  3342. ruleUrls.splice(u,1);
  3343. break;
  3344. }
  3345. }
  3346. for(let u=0;u<rulesData.sort.length;u++){
  3347. if(this.ruleUrl.id==rulesData.sort[u]){
  3348. rulesData.sort.splice(u,1);
  3349. break;
  3350. }
  3351. }
  3352. storage.setItem("rulesData", rulesData);
  3353. ruleParser.rules=ruleParser.rules.filter(item=>{return item.from!=this.ruleUrl.id});
  3354. storage.setItem("rules", ruleParser.rules);
  3355. this.item.parentNode.removeChild(this.item);
  3356. //location.reload();
  3357. }
  3358. }
  3359. }
  3360. let updateP=document.createElement("p"),i=0;
  3361. let now=new Date().getTime(),inUpdate=false;
  3362.  
  3363.  
  3364. let pastDate=(new Date(updateDate)).toString(),passStr;
  3365. let passTime=(now-updateDate)/1000;
  3366. if(isNaN(passTime)){
  3367. passStr=i18n("firstUpdate");
  3368. }else if(passTime<60){
  3369. passStr=i18n("passSec", parseInt(passTime))+" 👆 "+i18n("click2update");
  3370. }else if(passTime<60*60){
  3371. passStr=i18n("passMin", parseInt(passTime/60))+" 👆 "+i18n("click2update");
  3372. }else if(passTime<60*60*24){
  3373. passStr=i18n("passHour", parseInt(passTime/3600))+" 👆 "+i18n("click2update");
  3374. }else{
  3375. passStr=i18n("passDay", parseInt(passTime/86400))+" 👆 "+i18n("click2update");
  3376. }
  3377.  
  3378.  
  3379. updateP.className="updateDate";
  3380. updateP.innerHTML=passStr;
  3381. updateP.title=i18n("update")+" - "+pastDate;
  3382. updateP.onclick=e=>{
  3383. updateRules(()=>{
  3384. showTips(i18n("updateSucc"));
  3385. updateP.innerHTML=i18n("passSec", 0);
  3386. updateP.title=i18n("update");
  3387. },(rule,err)=>{
  3388. showTips("Update "+rule.url+" rules fail!");
  3389. });
  3390. showTips(i18n("beginUpdate"));
  3391. };
  3392. configCon.insertBefore(updateP, insertPos);
  3393. if(ruleUrls){
  3394. ruleUrls.forEach(ruleUrl=>{
  3395. var rulebar=new Rulebar();
  3396. rulebar.init(ruleUrl);
  3397. });
  3398. }
  3399. let customUrlsTitle=document.createElement("h2");
  3400. customUrlsTitle.innerHTML=i18n("customUrls");
  3401. configCon.insertBefore(customUrlsTitle, insertPos);
  3402. let customUrlsInput=document.createElement("textarea");
  3403. customUrlsInput.style.width="100%";
  3404. customUrlsInput.placeholder="http://wedata.net/databases/AutoPagerize/items_all.json";
  3405. customUrlsInput.spellcheck=false;
  3406. configCon.insertBefore(customUrlsInput, insertPos);
  3407.  
  3408. let btns=document.createElement("div");
  3409. btns.style.display="flex";
  3410. configCon.insertBefore(btns, insertPos);
  3411. let upBtnImg=document.createElement("div");
  3412. upBtnImg.style.width="50%";
  3413. let upBtnImgTitle=document.createElement("h2");
  3414. upBtnImgTitle.style.whiteSpace="nowrap";
  3415. upBtnImgTitle.style.overflow="auto";
  3416. upBtnImgTitle.innerHTML=i18n("upBtnImg");
  3417. upBtnImg.appendChild(upBtnImgTitle);
  3418. let upBtnImgInput=document.createElement("input");
  3419. upBtnImgInput.style.width="100%";
  3420. upBtnImgInput.placeholder="data:image/png;base64,UpBtn";
  3421. upBtnImgInput.value=rulesData.upBtnImg||'';
  3422. upBtnImgInput.spellcheck=false;
  3423. upBtnImg.appendChild(upBtnImgInput);
  3424. btns.appendChild(upBtnImg);
  3425.  
  3426. let downBtnImg=document.createElement("div");
  3427. downBtnImg.style.width="50%";
  3428. let downBtnImgTitle=document.createElement("h2");
  3429. downBtnImgTitle.style.whiteSpace="nowrap";
  3430. downBtnImgTitle.style.overflow="auto";
  3431. downBtnImgTitle.innerHTML=i18n("downBtnImg");
  3432. downBtnImg.appendChild(downBtnImgTitle);
  3433. let downBtnImgInput=document.createElement("input");
  3434. downBtnImgInput.style.width="100%";
  3435. downBtnImgInput.placeholder="data:image/png;base64,DownBtn";
  3436. downBtnImgInput.value=rulesData.downBtnImg||'';
  3437. downBtnImgInput.spellcheck=false;
  3438. downBtnImg.appendChild(downBtnImgInput);
  3439. btns.appendChild(downBtnImg);
  3440.  
  3441. let otherBtns=document.createElement("div");
  3442. otherBtns.style.display="flex";
  3443. configCon.insertBefore(otherBtns, insertPos);
  3444. let loadingText=document.createElement("div");
  3445. loadingText.style.width="100%";
  3446. let loadingTextTitle=document.createElement("h2");
  3447. loadingTextTitle.style.whiteSpace="nowrap";
  3448. loadingTextTitle.style.overflow="auto";
  3449. loadingTextTitle.innerHTML=i18n("loadingTextTitle");
  3450. loadingText.appendChild(loadingTextTitle);
  3451. let loadingTextInput=document.createElement("input");
  3452. loadingTextInput.value=rulesData.loadingText||'';
  3453. loadingTextInput.placeholder=i18n("loadingText");
  3454. loadingTextInput.style.width="100%";
  3455. loadingTextInput.style.margin="0";
  3456. loadingTextInput.spellcheck=false;
  3457. loadingText.appendChild(loadingTextInput);
  3458. otherBtns.appendChild(loadingText);
  3459.  
  3460. let opacity=document.createElement("div");
  3461. let opacityTitle=document.createElement("h2");
  3462. opacityTitle.style.whiteSpace="nowrap";
  3463. opacityTitle.style.overflow="visible";
  3464. opacityTitle.innerHTML=i18n("opacity");
  3465. opacity.appendChild(opacityTitle);
  3466. let opacityInput=document.createElement("input");
  3467. opacityInput.value=rulesData.opacity*100;
  3468. opacityInput.type="number";
  3469. opacityInput.style.width="110px";
  3470. opacityInput.style.margin="0";
  3471. opacityInput.placeholder=i18n("opacityPlaceholder");
  3472. opacityInput.spellcheck=false;
  3473. opacity.appendChild(opacityInput);
  3474. otherBtns.appendChild(opacity);
  3475.  
  3476. let pageElementCss=document.createElement("div");
  3477. pageElementCss.style.marginBottom="30px";
  3478. let pageElementCssTitle=document.createElement("h2");
  3479. pageElementCssTitle.innerHTML=i18n("pageElementCss");
  3480. pageElementCss.appendChild(pageElementCssTitle);
  3481. let pageElementCssInput=document.createElement("input");
  3482. pageElementCssInput.value=rulesData.pageElementCss||'';
  3483. pageElementCssInput.style.width="100%";
  3484. pageElementCssInput.style.margin="0";
  3485. pageElementCssInput.placeholder="font-size: xx-large;";
  3486. pageElementCssInput.spellcheck=false;
  3487. pageElementCss.appendChild(pageElementCssInput);
  3488. configCon.insertBefore(pageElementCss, insertPos);
  3489.  
  3490. let customCss=document.createElement("div");
  3491. customCss.style.marginBottom="50px";
  3492. let customCssTitle=document.createElement("h2");
  3493. customCssTitle.innerHTML=i18n("customCss");
  3494. customCss.appendChild(customCssTitle);
  3495. let customCssInput=document.createElement("textarea");
  3496. customCssInput.value=rulesData.customCss||'';
  3497. customCssInput.style.width="100%";
  3498. customCssInput.style.margin="0";
  3499. customCssInput.placeholder=".pagetual{\n}";
  3500. customCssInput.spellcheck=false;
  3501. customCss.appendChild(customCssInput);
  3502. configCon.insertBefore(customCss, insertPos);
  3503.  
  3504. let configTable=document.createElement("table");
  3505. configTable.style.width="100%";
  3506. let configTbody=document.createElement("tbody");
  3507. configTbody.style.width="100%";
  3508. configTbody.style.display="inline-table";
  3509. configTable.appendChild(configTbody);
  3510. configCon.insertBefore(configTable, insertPos);
  3511. function createCheckbox(innerText, val, tag, parentCheck, otherType) {
  3512. if (typeof val == 'undefined') val = "";
  3513. let title=document.createElement(tag || "h3");
  3514. title.innerHTML = innerText;
  3515. title.style.overflowWrap = "normal";
  3516. let input = document.createElement("input");
  3517. if (otherType === 'key') {
  3518. input.type = 'text';
  3519. input.setAttribute('readOnly', 'readonly');
  3520. input.addEventListener("keydown", e => {
  3521. if (e.key === 'Escape' || e.key === 'Backspace') input.value = '';
  3522. else input.value = e.key;
  3523. e.stopPropagation();
  3524. e.preventDefault();
  3525. });
  3526. } else {
  3527. input.type = otherType || "checkbox";
  3528. }
  3529. input.style.width = "30px";
  3530. input.style.height = "20px";
  3531. input.style.float = "left";
  3532. input.style.margin = "5px";
  3533. input.value = val;
  3534. input.checked = val;
  3535. let td = document.createElement("td");
  3536. td.appendChild(input);
  3537. if (parentCheck) {
  3538. title.style.margin = "0";
  3539. td.appendChild(title);
  3540. let parent = parentCheck.parentNode.nextElementSibling;
  3541. let tr = parent.querySelector("tr");
  3542. if (!tr) {
  3543. tr = document.createElement("tr");
  3544. parent.appendChild(tr);
  3545. }
  3546. tr.appendChild(td);
  3547. if (!parentCheck.checked) {
  3548. td.style.display = "none";
  3549. }
  3550. parentCheck.addEventListener("click", e => {
  3551. td.style.display = parentCheck.checked ? "" : "none";
  3552. });
  3553. } else {
  3554. let tr = document.createElement("tr");
  3555. tr.appendChild(td);
  3556. td = document.createElement("td");
  3557. td.appendChild(title);
  3558. tr.appendChild(td);
  3559. configTable.children[0].appendChild(tr);
  3560. }
  3561. return input;
  3562. }
  3563.  
  3564. let enableWhiteListInput=createCheckbox(i18n("autoRun"), rulesData.enableWhiteList!=true);
  3565. let enableDebugInput=createCheckbox(i18n("enableDebug"), rulesData.enableDebug!=false);
  3566. let enableHistoryInput=createCheckbox(i18n("enableHistory"), rulesData.enableHistory===true);
  3567. let enableHistoryAfterInsertInput=createCheckbox(i18n("enableHistoryAfterInsert"), rulesData.enableHistoryAfterInsert===true);
  3568. let openInNewTabInput=createCheckbox(i18n("openInNewTab"), rulesData.openInNewTab!=false);
  3569. let hideLoadingIconInput=createCheckbox(i18n("hideLoadingIcon"), rulesData.hideLoadingIcon!=false);
  3570. let initRunInput=createCheckbox(i18n("initRun"), rulesData.initRun!=false);
  3571. let autoLoadNumInput=createCheckbox(i18n("autoLoadNum"), rulesData.autoLoadNum, "h4", initRunInput, "number");
  3572. let preloadInput=createCheckbox(i18n("preload"), rulesData.preload!=false);
  3573. let dbClick2StopInput=createCheckbox(i18n("dbClick2Stop"), rulesData.dbClick2Stop);
  3574. let manualModeInput=createCheckbox(i18n("manualMode"), rulesData.manualMode);
  3575. let clickModeInput=createCheckbox(i18n("clickMode"), rulesData.clickMode);
  3576. let pageBarMenuInput=createCheckbox(i18n("pageBarMenu"), rulesData.pageBarMenu);
  3577. let arrowToScrollInput=createCheckbox(i18n("arrowToScroll"), rulesData.arrowToScroll);
  3578.  
  3579. let hideBarInput = createCheckbox(i18n("hideBar"), rulesData.hideBar && !rulesData.hideBarButNoStop, "h4", dbClick2StopInput, 'radio');
  3580. hideBarInput.name = 'hideBar';
  3581. let hideBarButNoStopInput = createCheckbox(i18n("hideBarButNoStop"), rulesData.hideBarButNoStop, "h4", dbClick2StopInput, 'radio');
  3582. hideBarButNoStopInput.name = 'hideBar';
  3583. hideBarInput.addEventListener('mouseup', e => {
  3584. if (hideBarInput.checked) {
  3585. setTimeout(() => {hideBarInput.checked = false}, 0);
  3586. }
  3587. });
  3588. hideBarButNoStopInput.addEventListener('mouseup', e => {
  3589. if (hideBarButNoStopInput.checked) {
  3590. setTimeout(() => {hideBarButNoStopInput.checked = false}, 0);
  3591. }
  3592. });
  3593.  
  3594. let dbClick2StopCtrlInput=createCheckbox(i18n("dbClick2StopCtrl"), rulesData.dbClick2StopCtrl, "h4", dbClick2StopInput);
  3595. let dbClick2StopAltInput=createCheckbox(i18n("dbClick2StopAlt"), rulesData.dbClick2StopAlt, "h4", dbClick2StopInput);
  3596. let dbClick2StopShiftInput=createCheckbox(i18n("dbClick2StopShift"), rulesData.dbClick2StopShift, "h4", dbClick2StopInput);
  3597. let dbClick2StopMetaInput=createCheckbox(i18n("dbClick2StopMeta"), rulesData.dbClick2StopMeta, "h4", dbClick2StopInput);
  3598. let dbClick2StopKeyInput=createCheckbox(i18n("dbClick2StopKey"), rulesData.dbClick2StopKey, "h4", dbClick2StopInput, "key");
  3599.  
  3600. let customRulesTitle=document.createElement("h2");
  3601. customRulesTitle.innerHTML=i18n("customRules");
  3602. configCon.insertBefore(customRulesTitle, insertPos);
  3603. let customRulesInput=document.createElement("textarea");
  3604. customRulesInput.spellcheck=false;
  3605. configCon.insertBefore(customRulesInput, insertPos);
  3606. if(rulesData.editTemp){
  3607. if(!ruleParser.customRules){
  3608. ruleParser.customRules=[];
  3609. }
  3610. for(let i in ruleParser.customRules){
  3611. if(ruleParser.customRules[i].url==rulesData.editTemp.url){
  3612. ruleParser.customRules.splice(i, 1);
  3613. break;
  3614. }
  3615. }
  3616. ruleParser.customRules.unshift(rulesData.editTemp);
  3617. rulesData.editTemp=null;
  3618. storage.setItem("rulesData", rulesData);
  3619. customRulesInput.previousElementSibling.scrollIntoView();
  3620. }
  3621. customRulesInput.style.width="100%";
  3622. customRulesInput.style.height="800px";
  3623. 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]`;
  3624. customRulesInput.value=getFormatJSON(ruleParser.customRules);
  3625. let blacklistInput=document.createElement("textarea");
  3626. blacklistInput.style.width="100%";
  3627. blacklistInput.style.height="500px";
  3628. blacklistInput.style.display="none";
  3629. blacklistInput.spellcheck=false;
  3630. blacklistInput.placeholder="http://*.xxx.com/*/y";
  3631. blacklistInput.value=rulesData.blacklist?rulesData.blacklist.join("\n"):"";
  3632. let blacklistBtn=document.createElement("button");
  3633. blacklistBtn.innerText=i18n("editBlacklist");
  3634. blacklistBtn.style.width="100%";
  3635. blacklistBtn.onclick=e=>{
  3636. blacklistInput.style.display=blacklistInput.style.display=="none"?"":"none";
  3637. };
  3638. configCon.insertBefore(blacklistBtn, insertPos);
  3639. configCon.insertBefore(blacklistInput, insertPos);
  3640. let saveBtn=document.createElement("button");
  3641. saveBtn.innerHTML=i18n("save");
  3642. saveBtn.style.width="100%";
  3643. saveBtn.style.position="fixed";
  3644. saveBtn.style.zIndex="999";
  3645. saveBtn.style.bottom=0;
  3646. saveBtn.style.left=0;
  3647. saveBtn.style.fontSize="x-large";
  3648. configCon.insertBefore(saveBtn, insertPos);
  3649. saveBtn.onclick=e=>{
  3650. try{
  3651. storage.setItem("hpRules", []);
  3652. storage.setItem("smartRules", []);
  3653. if(customRulesInput.value==""){
  3654. storage.setItem("customRules", "");
  3655. }else{
  3656. let customRules=JSON.parse(customRulesInput.value);
  3657. if(Array && Array.isArray && !Array.isArray(customRules)){
  3658. showTips("Rules must be a Array!");
  3659. return;
  3660. }
  3661. debug(customRules);
  3662. storage.setItem("customRules", customRules);
  3663. customRulesInput.value=JSON.stringify(customRules, null, 4);
  3664. }
  3665. }catch(e){
  3666. debug(e);
  3667. showTips("JSON error, check again!");
  3668. return;
  3669. }
  3670. rulesData.opacity = opacityInput.value / 100;
  3671. rulesData.blacklist = blacklistInput.value ? blacklistInput.value.split("\n") : "";
  3672. rulesData.hideBar = hideBarInput.checked;
  3673. rulesData.hideBarButNoStop = hideBarButNoStopInput.checked;
  3674. rulesData.dbClick2Stop = dbClick2StopInput.checked;
  3675. rulesData.enableWhiteList = !enableWhiteListInput.checked;
  3676. rulesData.enableDebug = enableDebugInput.checked;
  3677. rulesData.enableHistory = enableHistoryInput.checked;
  3678. rulesData.enableHistoryAfterInsert = enableHistoryAfterInsertInput.checked;
  3679. rulesData.openInNewTab = openInNewTabInput.checked;
  3680. rulesData.hideLoadingIcon = hideLoadingIconInput.checked;
  3681. rulesData.initRun = initRunInput.checked;
  3682. rulesData.autoLoadNum = autoLoadNumInput.value !== "0" ? autoLoadNumInput.value : '';
  3683. rulesData.preload = preloadInput.checked;
  3684. rulesData.manualMode = manualModeInput.checked;
  3685. rulesData.clickMode = clickModeInput.checked;
  3686. rulesData.pageBarMenu = pageBarMenuInput.checked;
  3687. rulesData.arrowToScroll = arrowToScrollInput.checked;
  3688. rulesData.pageElementCss = pageElementCssInput.value;
  3689. rulesData.customCss = customCssInput.value;
  3690. rulesData.upBtnImg = upBtnImgInput.value;
  3691. rulesData.downBtnImg = downBtnImgInput.value;
  3692. rulesData.loadingText = loadingTextInput.value;
  3693. rulesData.dbClick2StopCtrl = dbClick2StopCtrlInput.checked;
  3694. rulesData.dbClick2StopAlt = dbClick2StopAltInput.checked;
  3695. rulesData.dbClick2StopShift = dbClick2StopShiftInput.checked;
  3696. rulesData.dbClick2StopMeta = dbClick2StopMetaInput.checked;
  3697. rulesData.dbClick2StopKey = dbClick2StopKeyInput.value;
  3698. storage.setItem("rulesData", rulesData);
  3699. let customUrls = customUrlsInput.value.trim();
  3700. if (customUrls) {
  3701. customUrls = customUrls.split(/\n/);
  3702. for (let c = 0; c < customUrls.length; c++) {
  3703. let url;
  3704. if(/^0\s*\|/.test(customUrls[c])){
  3705. url=customUrls[c].replace(/^0\s*\|\s*/, "").trim();
  3706. if(!/^http/.test(url)){
  3707. showTips("Wrong url, check again!");
  3708. return;
  3709. }
  3710. }else{
  3711. url=customUrls[c].trim();
  3712. if(!/^http/.test(url)){
  3713. showTips("Wrong url, check again!");
  3714. return;
  3715. }
  3716. }
  3717. let maxId=1,hasUrl=false;
  3718. if(!rulesData.urls){
  3719. rulesData.urls=[];
  3720. }
  3721. ruleUrls.forEach(u=>{
  3722. if(maxId<u.id){
  3723. maxId=u.id;
  3724. }
  3725. if(u.url==url){
  3726. hasUrl=true;
  3727. }
  3728. });
  3729. if(hasUrl)break;
  3730. if(!rulesData.sort)rulesData.sort=[1];
  3731. rulesData.urls.push({id:maxId+1,url:url});
  3732. rulesData.sort.push(maxId+1);
  3733. storage.setItem("rulesData", rulesData);
  3734. }
  3735. }
  3736. showTips("The settings are saved, refresh to view");
  3737. //location.reload();
  3738. };
  3739. return true;
  3740. }
  3741.  
  3742. var inUpdate=false;
  3743. function updateRules(success,fail){
  3744. if(inUpdate)return;
  3745. inUpdate=true;
  3746. let ruleIndex=ruleUrls.length-1;
  3747. storage.setItem("hpRules", []);
  3748. storage.setItem("smartRules", []);
  3749. function addNextRule(){
  3750. if(ruleIndex<0){
  3751. let now=new Date().getTime();
  3752. storage.setItem("ruleLastUpdate", now);
  3753. storage.setItem("rules", ruleParser.rules);
  3754. inUpdate=false;
  3755. success();
  3756. }else{
  3757. let rule=ruleUrls[ruleIndex--];
  3758. ruleParser.addRuleByUrl(rule.url, rule.id, (json,err)=>{
  3759. if(!json){
  3760. fail(rule,err);
  3761. }
  3762. addNextRule();
  3763. })
  3764. }
  3765. }
  3766. addNextRule();
  3767. }
  3768.  
  3769. function objIsArr(obj) {
  3770. return obj &&
  3771. typeof obj === 'object' &&
  3772. typeof obj.length === 'number' &&
  3773. !(obj.propertyIsEnumerable('length'));
  3774. }
  3775.  
  3776. function isVisible(el, win) {
  3777. if(!el || !el.offsetParent)return false;
  3778. var loopable = true,
  3779. visible = el.tagName && win.getComputedStyle(el).display != 'none' && win.getComputedStyle(el).visibility != 'hidden';
  3780. while(loopable && visible) {
  3781. el = el.parentNode;
  3782.  
  3783. if(el && el.tagName && el.tagName!="BODY") {
  3784. visible = win.getComputedStyle(el).display != 'none' && win.getComputedStyle(el).visibility != 'hidden';
  3785. }else {
  3786. loopable = false;
  3787. }
  3788. }
  3789. return visible;
  3790. }
  3791.  
  3792. function getElementTop(ele) {
  3793. if (!ele) return 0;
  3794. var actualTop = ele.offsetTop;
  3795. var current = ele.offsetParent;
  3796. while (current) {
  3797. actualTop += current.offsetTop;
  3798. current = current.offsetParent;
  3799. }
  3800. return actualTop;
  3801. }
  3802.  
  3803. function getElementBottom(ele) {
  3804. return getElementTop(ele) + ele.offsetHeight;
  3805. }
  3806.  
  3807. function getFormatJSON(obj){
  3808. if(!objIsArr(obj) || obj.length === 0)return "";
  3809. return JSON.stringify(obj, null, 4);
  3810. let ret="[\n";
  3811. let len=obj.length,i=0,isLast;
  3812. obj.forEach(item=>{
  3813. ret+=" {\n";
  3814. let iLen=Object.keys(item).length,j=0;
  3815. for(let key in item){
  3816. isLast=(++j)==iLen;
  3817. let value=item[key];
  3818. if(objIsArr(value)){
  3819. let vstr="[",v=0,vIsLast=false;
  3820. value.forEach(vi=>{
  3821. vIsLast=(++v)==value.length;
  3822. vstr+="\""+vi.replace(/\\/g,"\\\\")+"\""+(vIsLast?"":",");
  3823. });
  3824. vstr+="]";
  3825. ret+=" \""+key+"\":"+vstr+""+(isLast?"":",")+"\n";
  3826. }else{
  3827. if(typeof value=="string"){
  3828. value=value.replace(/\\/g,"\\\\").replace(/"/g,"\\\"");
  3829. value="\""+value+"\"";
  3830. }
  3831. ret+=" \""+key+"\":"+value+""+(isLast?"":",")+"\n";
  3832. }
  3833. }
  3834. isLast=(++i)==len;
  3835. ret+=" }"+(isLast?"":",")+"\n";
  3836. });
  3837. ret+="]";
  3838. return ret;
  3839. }
  3840.  
  3841. function globMatch(first, second) {
  3842. if (first.length == 0 && second.length == 0){
  3843. return true;
  3844. }
  3845.  
  3846. if (first.length > 1 && first[0] == '*' &&
  3847. second.length == 0){
  3848. return false;
  3849. }
  3850.  
  3851. if ((first.length > 1 && first[0] == '?') ||
  3852. (first.length != 0 && second.length != 0 &&
  3853. first[0] == second[0])){
  3854. return globMatch(first.substring(1),
  3855. second.substring(1));
  3856. }
  3857.  
  3858. if (first.length > 0 && first[0] == '*'){
  3859. return globMatch(first.substring(1), second) ||
  3860. globMatch(first, second.substring(1));
  3861. }
  3862.  
  3863. return false;
  3864. }
  3865.  
  3866. function initRules(callback) {
  3867. /*0 wedata格式,1 pagetual格式*/
  3868. ruleUrls=[
  3869. {
  3870. id:1,
  3871. url:'http://wedata.net/databases/AutoPagerize/items_all.json',
  3872. type:0,
  3873. }
  3874. ];var i=0,j=0;
  3875.  
  3876. ruleParser.initSavedRules(()=>{
  3877. storage.getItem("rulesData", data=>{
  3878. if(data){
  3879. rulesData=data;
  3880. if(data.urls)ruleUrls=ruleUrls.concat(data.urls);
  3881. if(data.sort){
  3882. let urls=[];
  3883. data.sort.forEach(id=>{
  3884. for(let s=0;s<ruleUrls.length;s++){
  3885. if(id==ruleUrls[s].id){
  3886. urls.push(ruleUrls[s]);
  3887. break;
  3888. }
  3889. }
  3890. });
  3891. ruleUrls=urls;
  3892. }
  3893. }
  3894. let upBtnImg=rulesData.upBtnImg,downBtnImg=rulesData.downBtnImg;
  3895. if(upBtnImg && downBtnImg){
  3896. downSvgCSS=downSvgCSS.replace("transform: rotate(180deg);","");
  3897. }else if(upBtnImg && !downBtnImg){
  3898. downBtnImg=upBtnImg;
  3899. }else if(downBtnImg && !upBtnImg){
  3900. upBtnImg=downBtnImg;
  3901. }
  3902. if(upBtnImg){
  3903. upSvg=`<img class="pagetual" src="${upBtnImg}"/>`;
  3904. }
  3905. if(downBtnImg){
  3906. downSvg=`<img class="pagetual" src="${downBtnImg}"/>`;
  3907. }
  3908. setLoadingDiv(rulesData.loadingText || i18n("loadingText"));
  3909. if(typeof(rulesData.opacity)=="undefined"){
  3910. rulesData.opacity=0.3;
  3911. }
  3912. if(typeof(rulesData.hideBar)=="undefined"){
  3913. rulesData.hideBar=false;
  3914. }
  3915. if(typeof(rulesData.dbClick2Stop)=="undefined"){
  3916. rulesData.dbClick2Stop=true;
  3917. }
  3918. if(typeof(rulesData.enableWhiteList)=="undefined"){
  3919. rulesData.enableWhiteList=false;
  3920. }
  3921. if(typeof(rulesData.enableHistory)=="undefined"){
  3922. rulesData.enableHistory=false;
  3923. }
  3924. if(typeof(rulesData.openInNewTab)=="undefined"){
  3925. rulesData.openInNewTab=true;
  3926. }
  3927. if(typeof(rulesData.enableDebug)=="undefined"){
  3928. rulesData.enableDebug=true;
  3929. }
  3930. if(typeof(rulesData.initRun)=="undefined"){
  3931. rulesData.initRun=true;
  3932. }
  3933. if(typeof(rulesData.preload)=="undefined"){
  3934. rulesData.preload=true;
  3935. }
  3936. if(typeof(rulesData.manualMode)=="undefined"){
  3937. rulesData.manualMode=false;
  3938. }
  3939. if(typeof(rulesData.clickMode)=="undefined"){
  3940. rulesData.clickMode=false;
  3941. }
  3942. if(typeof(rulesData.pageBarMenu)=="undefined"){
  3943. rulesData.pageBarMenu=false;
  3944. }
  3945. if(typeof(rulesData.arrowToScroll)=="undefined"){
  3946. rulesData.arrowToScroll=false;
  3947. }
  3948. if(typeof(rulesData.hideLoadingIcon)=="undefined"){
  3949. rulesData.hideLoadingIcon=false;
  3950. }
  3951. if(rulesData.blacklist && rulesData.blacklist.length>0){
  3952. for(let b in rulesData.blacklist){
  3953. let curGlob=rulesData.blacklist[b];
  3954. if(globMatch(curGlob, location.href)){
  3955. return;
  3956. }
  3957. }
  3958. }
  3959. if(rulesData.autoLoadNum){
  3960. autoLoadNum=parseInt(rulesData.autoLoadNum);
  3961. }
  3962. enableDebug=rulesData.enableDebug;
  3963. storage.getItem("nextSwitch_"+location.host, i=>{
  3964. storage.getItem("forceState_"+location.host, v=>{
  3965. storage.getItem("ruleLastUpdate", date=>{
  3966. if(typeof(i)!=="undefined"){
  3967. nextIndex=i;
  3968. }
  3969. if(typeof(v)=="undefined"){
  3970. v=(rulesData.enableWhiteList?1:0);
  3971. }
  3972. forceState=v;
  3973. updateDate=date;
  3974. if(initConfig())return;
  3975. if(forceState==1)return;
  3976. let now=new Date().getTime();
  3977. if(!date || now-date>2*24*60*60*1000){
  3978. updateRules(()=>{
  3979. },(rule,err)=>{});
  3980. storage.setItem("ruleLastUpdate", now);
  3981. }
  3982. callback();
  3983. });
  3984. });
  3985. });
  3986. });
  3987. });
  3988. }
  3989.  
  3990. function requestDoc(url, callback){
  3991. let postParams = url.match(/#p{(.*)}$/);
  3992. if (postParams) {
  3993. postParams = postParams[1];
  3994. url = url.replace(/#p{.*/, "");
  3995. }
  3996. _GM_xmlhttpRequest({
  3997. url: url,
  3998. method: postParams ? 'POST' : 'GET',
  3999. data: postParams,
  4000. overrideMimeType: 'text/html;charset=' + (document.characterSet || document.charset || document.inputEncoding),
  4001. headers: {
  4002. 'Referer': location.href,
  4003. 'User-Agent': navigator.userAgent,
  4004. "Content-Type": (postParams ? "application/x-www-form-urlencoded" : "text/html") + ";charset=" + (document.characterSet || document.charset || document.inputEncoding),
  4005. },
  4006. timeout: 10000,
  4007. onload: function(res) {
  4008. var doc=null,response=res.response;
  4009. let preCode=ruleParser.curSiteRule.pageElementPre || ruleParser.curSiteRule.pagePre;
  4010. if(preCode){
  4011. try{
  4012. if (typeof _unsafeWindow.pagetualPagePre!='undefined') {
  4013. response = _unsafeWindow.pagetualPagePre(response);
  4014. } else if (preCode.length == 2) {
  4015. response = response.replace(new RegExp(preCode[0], "gi"), preCode[1]);
  4016. } else {
  4017. response = Function("response",'"use strict";' + preCode)(response);
  4018. }
  4019. }catch(e){
  4020. debug(e);
  4021. }
  4022. }
  4023. try {
  4024. doc=document.implementation.createHTMLDocument('');
  4025. doc.documentElement.innerHTML=response;
  4026. let base=doc.querySelector("base");
  4027. ruleParser.basePath=base?base.href:url;
  4028. }
  4029. catch (e) {
  4030. debug('parse error'+e.toString());
  4031. }
  4032. let pageElement=ruleParser.getPageElement(doc);
  4033. if(inCors && (!pageElement || pageElement.length==0)){
  4034. ruleParser.curSiteRule.pageElement=allOfBody;
  4035. pageElement=ruleParser.getPageElement(doc);
  4036. ruleParser.getInsert(true);
  4037. }
  4038. //只有1的話怕不是圖片哦
  4039. if(pageElement && (pageElement.length>1 || (pageElement.length==1 && pageElement[0].tagName!="IMG") )){
  4040. ruleParser.insertPage(doc, pageElement, url, callback, false);
  4041. if(ruleParser.curSiteRule.action==1){
  4042. requestFromIframe(url, (doc, eles)=>{
  4043. loadPageOver();
  4044. if(eles){
  4045. ruleParser.insertPage(doc, eles, url, callback, true);
  4046. }
  4047. });
  4048. }else ruleParser.curSiteRule.action=0;
  4049. }else if(ruleParser.curSiteRule.singleUrl || curPage==1){
  4050. ruleParser.curSiteRule.action=1;
  4051. requestFromIframe(url, (doc, eles)=>{
  4052. loadPageOver();
  4053. if(eles){
  4054. ruleParser.insertPage(doc, eles, url, callback, true);
  4055. }
  4056. });
  4057. }else{
  4058. debug("Stop as no page element");
  4059. isPause=true;
  4060. callback(false);
  4061. }
  4062. },
  4063. onerror: function(e){
  4064. debug(e);
  4065. callback(false);
  4066. },
  4067. ontimeout: function(e){
  4068. debug(e);
  4069. callback(false);
  4070. }
  4071. });
  4072. }
  4073.  
  4074. function initPage(){
  4075. ruleParser.initPage(()=>{
  4076. if(ruleParser.curSiteRule.autoLoadNum){
  4077. autoLoadNum=ruleParser.curSiteRule.autoLoadNum;
  4078. }
  4079. if(ruleParser.curSiteRule.nextLink && Array && Array.isArray && Array.isArray(ruleParser.curSiteRule.nextLink)){
  4080. _GM_registerMenuCommand(i18n("nextSwitch"), ()=>{
  4081. NextSwitch.getInstance().start();
  4082. });
  4083. }
  4084. if(ruleParser.nextLinkHref){
  4085. let isJs=/^(javascript|#)/.test(ruleParser.nextLinkHref.replace(location.href,""));
  4086. if(!isJs){
  4087. let inForce=(forceState == 2 || forceState == 3);
  4088. _GM_registerMenuCommand(i18n(inForce?"cancelForceIframe":"forceIframe"), ()=>{
  4089. if(inForce){
  4090. storage.setItem("forceState_"+location.host, "");
  4091. }else{
  4092. let _state=ruleParser.curSiteRule.action>0 || confirm(i18n("forceAllBody"))?2:3;
  4093. storage.setItem("forceState_"+location.host, _state);
  4094. }
  4095. location.reload();
  4096. });
  4097. }
  4098. _GM_registerMenuCommand(i18n("loadNow"), ()=>{
  4099. let loadNum=window.prompt(i18n("loadConfirm"), "1");
  4100. if(loadNum==="" || loadNum===null)return;
  4101. autoLoadNum=Math.abs(parseInt(loadNum));
  4102. nextPage();
  4103. });
  4104. }
  4105. initListener();
  4106. let initRun = typeof ruleParser.curSiteRule.initRun == 'undefined' ? rulesData.initRun : ruleParser.curSiteRule.initRun;
  4107. if (initRun && initRun != 0 && initRun != '0') nextPage();
  4108. });
  4109. }
  4110.  
  4111. var pageBarStyle;
  4112. function initView(){
  4113. _GM_addStyle(`
  4114. .pagetual_pageBar{
  4115. -moz-transition:opacity 0.3s ease-in-out 0s;
  4116. -webkit-transition:opacity 0.3s ease-in-out 0s;
  4117. transition:opacity 0.3s ease-in-out 0s;
  4118. font-family: Arial,sans-serif !important;
  4119. }
  4120. .pagetual_pageBar.stop {
  4121. -webkit-filter: invert(100%);
  4122. filter: invert(100%);
  4123. opacity: 1!important;
  4124. }
  4125. .pagetual_pageBar.hide {
  4126. display: none!important;
  4127. }
  4128. .pagetual_pageBar:hover {
  4129. opacity: 1!important;
  4130. }
  4131. .pagetual_pageBar span {
  4132. vertical-align: super;
  4133. }
  4134. .pagetual_pageBar a::before,
  4135. .pagetual_pageBar a::after {
  4136. content: none;
  4137. }
  4138. .pagetual_pageBar a>span {
  4139. margin-top: 0!important;
  4140. pointer-events: none;
  4141. padding: unset;
  4142. opacity: 0;
  4143. -moz-transition:all 0.3s ease-in-out 0s;
  4144. -webkit-transition:all 0.3s ease-in-out 0s;
  4145. transition:all 0.3s ease-in-out 0s;
  4146. }
  4147. .pagetual_pageBar a>span:hover {
  4148. color: red;
  4149. }
  4150. .pagetual_pageBar a:hover>span {
  4151. opacity: 1;
  4152. }
  4153. .pagetual_pageBar span.prevScreen,
  4154. .pagetual_pageBar span.nextScreen {
  4155. display: block!important;
  4156. }
  4157. .pagetual_pageBar a:hover>span.prevScreen {
  4158. margin-top: -30px!important;
  4159. pointer-events: all;
  4160. }
  4161. .pagetual_pageBar a:hover>span.nextScreen {
  4162. margin-top: 30px!important;
  4163. pointer-events: all;
  4164. }
  4165. .pagetual_pageBar span>svg {
  4166. -moz-transition:transform 0.5s ease, opacity 0.3s ease;
  4167. -webkit-transition:transform 0.5s ease, opacity 0.3s ease;
  4168. transition:transform 0.5 ease, opacity 0.3s ease;
  4169. opacity: 0;
  4170. }
  4171. .pagetual_pageBar:hover span>svg {
  4172. opacity: 1;
  4173. }
  4174. .pagetual_pageBar span>svg.upSvg:hover {
  4175. transform: rotate(360deg) scale3d(1.2, 1.2, 1.2);
  4176. }
  4177. .pagetual_pageBar span>svg.downSvg:hover {
  4178. transform: rotate(540deg) scale3d(1.2, 1.2, 1.2)!important;
  4179. }
  4180. .pagetual_pageBar .pagetual_pageNum{
  4181. color: #55555f;
  4182. }
  4183. .pagetual_pageBar .pagetual_pageNum:hover{
  4184. color: #ff6464;
  4185. }
  4186. .pagetual_tipsWords{
  4187. font-size: 50px;
  4188. font-weight: bold;
  4189. font-family: "黑体", -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto",
  4190. "Oxygen", "Ubuntu", "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji",
  4191. "Segoe UI Emoji", "Segoe UI Symbol";
  4192. color: #ffffff;
  4193. min-height: 70px;
  4194. max-width: 80%;
  4195. line-height: 70px;
  4196. position: fixed;
  4197. left: 50%;
  4198. top: 10%;
  4199. margin-left: -99999px;
  4200. padding: 0 15px;
  4201. z-index: 999999999;
  4202. background-color: #000;
  4203. border: 1px solid #303030;
  4204. border-radius: 10px;
  4205. opacity: 0;
  4206. filter: alpha(opacity=65);
  4207. box-shadow: 5px 5px 20px 0px #000;
  4208. -moz-transition:opacity 0.3s ease-in-out 0s;
  4209. -webkit-transition:opacity 0.3s ease-in-out 0s;
  4210. transition:opacity 0.3s ease-in-out 0s;
  4211. pointer-events: none;
  4212. }
  4213. .pagetual_loading {
  4214. width: 50px;
  4215. height: 50px;
  4216. margin: 10px auto;
  4217. border-radius: 100%;
  4218. display: flex;
  4219. -webkit-animation: pagetual_loading_scaleout 1.0s infinite ease-in-out;
  4220. animation: pagetual_loading_scaleout 1.0s infinite ease-in-out;
  4221. }
  4222. @-webkit-keyframes pagetual_loading_scaleout {
  4223. 0% { -webkit-transform: scale(0.0) }
  4224. 100% {
  4225. -webkit-transform: scale(1.0);
  4226. opacity: 0;
  4227. }
  4228. }
  4229. @keyframes pagetual_loading_scaleout {
  4230. 0% {
  4231. transform: scale(0.0);
  4232. -webkit-transform: scale(0.0);
  4233. } 100% {
  4234. transform: scale(1.0);
  4235. -webkit-transform: scale(1.0);
  4236. opacity: 0;
  4237. }
  4238. }
  4239. .pagetual_loading_text {
  4240. white-space: nowrap;
  4241. -webkit-animation: pagetual_loading_opacity 2.6s infinite ease-in-out;
  4242. animation: pagetual_loading_opacity 2.6s infinite ease-in-out;
  4243. }
  4244. @-webkit-keyframes pagetual_loading_opacity {
  4245. 0% { opacity: 1 }
  4246. 50% { opacity: 0.2 }
  4247. 100% { opacity: 1 }
  4248. }
  4249. @keyframes pagetual_loading_opacity {
  4250. 0% { opacity: 1 }
  4251. 50% { opacity: 0.2 }
  4252. 100% { opacity: 1 }
  4253. }
  4254. `);
  4255. 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;`;
  4256. }
  4257. var loadingDiv=document.createElement("div");
  4258. 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;";
  4259.  
  4260. 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;`;
  4261. function setLoadingDiv(loadingText){
  4262. 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>`}`;
  4263. }
  4264.  
  4265. 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>`;
  4266. var upSvgCSS=`display:initial;position:relative;cursor: pointer;margin: 0 8px;width: 30px;height: 30px;vertical-align: middle;fill: currentColor;overflow: hidden;`;
  4267. 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>`;
  4268. 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);`;
  4269.  
  4270. 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;`;
  4271. 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;`;
  4272.  
  4273. var tipsWords=document.createElement("div");
  4274. tipsWords.className="pagetual_tipsWords";
  4275.  
  4276. var isPause = false, isHideBar = false, isLoading = false, curPage = 1, forceState = 0, bottomGap = 1000, autoLoadNum = -1, nextIndex = 0, stopScroll = false;
  4277.  
  4278. function changeStop(stop) {
  4279. isPause = stop;
  4280. [].forEach.call(document.querySelectorAll(".pagetual_pageBar"), bar => {
  4281. if (isPause) {
  4282. bar.classList.add("stop");
  4283. } else {
  4284. bar.classList.remove("stop");
  4285. }
  4286. });
  4287. }
  4288.  
  4289. function changeHideBar(hide) {
  4290. isHideBar = hide;
  4291. [].forEach.call(document.querySelectorAll(".pagetual_pageBar"), bar => {
  4292. if (isHideBar) {
  4293. bar.classList.add("hide");
  4294. } else {
  4295. bar.classList.remove("hide");
  4296. }
  4297. });
  4298. }
  4299.  
  4300. function isInViewPort(element) {
  4301. if(!document.body.contains(element))return false;
  4302. if(_unsafeWindow.getComputedStyle(element).display=="none")return false;
  4303. const viewWidth = window.innerWidth || document.documentElement.clientWidth;
  4304. const viewHeight = window.innerHeight || document.documentElement.clientHeight;
  4305. const {
  4306. top,
  4307. right,
  4308. bottom,
  4309. left,
  4310. } = element.getBoundingClientRect();
  4311.  
  4312. return (
  4313. top >= 0 &&
  4314. left >= 0 &&
  4315. right <= viewWidth + 1 &&
  4316. bottom <= viewHeight * 2
  4317. );
  4318. }
  4319.  
  4320. var urlChanged=false;
  4321. var _wr = function(type) {
  4322. var orig = history[type];
  4323. return function() {
  4324. var rv = orig.apply(this, arguments);
  4325. var e = new Event(type);
  4326. e.arguments = arguments;
  4327. window.dispatchEvent(e);
  4328. return rv;
  4329. };
  4330. };
  4331. var changeHandler = e => {
  4332. urlChanged = true;
  4333. isPause = true;
  4334. setTimeout(() => {
  4335. lastActiveUrl = location.href;
  4336. if (location.href == configPage[0] || guidePage.test(location.href)) {
  4337. location.reload();
  4338. } else if (!ruleParser.ruleMatch(ruleParser.curSiteRule)) {
  4339. initPage();
  4340. }
  4341. if (!ruleParser.nextLinkHref) isLoading = false;
  4342. },1);
  4343. };
  4344. history.pushState = _wr('pushState');
  4345. window.addEventListener('pushState', changeHandler);
  4346.  
  4347. function initListener(){
  4348. let loadmoreBtn,loading=true,lastScroll=0,checkLoadMoreTimes=0;
  4349. if (ruleParser.curSiteRule.loadMore) {
  4350. loading=false;
  4351. } else {
  4352. let checkLoadMore=setInterval(()=>{
  4353. loadmoreBtn=getLoadMore(document);
  4354. if(loadmoreBtn && isVisible(loadmoreBtn, _unsafeWindow)){
  4355. loading=false;
  4356. clearInterval(checkLoadMore);
  4357. }else if(checkLoadMoreTimes++>30){
  4358. clearInterval(checkLoadMore);
  4359. }
  4360. },300);
  4361. }
  4362. let clickMode = typeof ruleParser.curSiteRule.clickMode == 'undefined' ? rulesData.clickMode : ruleParser.curSiteRule.clickMode;
  4363. let clickNext = async () => {
  4364. let nextLink = ruleParser.nextLinkHref;
  4365. if (!nextLink) return;
  4366. let isJs = /^(javascript|#)/.test(nextLink.replace(location.href, ""));
  4367. if (isJs) {
  4368. let nextBtn = await ruleParser.getNextLink(document);
  4369. if (nextBtn) emuClick(nextBtn);
  4370. } else {
  4371. window.location.href = nextLink;
  4372. }
  4373. };
  4374. let checkScrollReach=()=>{
  4375. let scrolly=window.scrollY;
  4376. let windowHeight=window.innerHeight || document.documentElement.clientHeight;
  4377. let scrollH=Math.max(document.documentElement.scrollHeight, document.body.scrollHeight);
  4378. if(clickMode){
  4379. if(scrollH-scrolly-windowHeight<10){
  4380. clickNext();
  4381. }
  4382. }else if(scrollH-scrolly-windowHeight<bottomGap){
  4383. nextPage();
  4384. }
  4385. };
  4386. let scrollHandler = e=>{
  4387. if(urlChanged && !isLoading){
  4388. ruleParser.initPage(()=>{
  4389. if(ruleParser.nextLinkHref){
  4390. initView();
  4391. }
  4392. isPause=false;
  4393. });
  4394. urlChanged=false;
  4395. }
  4396. if(isPause)return;
  4397. if(!loading){
  4398. if(ruleParser.curSiteRule.loadMore || !loadmoreBtn || !document.body.contains(loadmoreBtn)){
  4399. loadmoreBtn=getLoadMore(document);
  4400. }
  4401. if(loadmoreBtn){
  4402. if(isInViewPort(loadmoreBtn)){
  4403. emuClick(loadmoreBtn);
  4404. loading=true;
  4405. setTimeout(()=>{loading=false},200);
  4406. }
  4407. }else{
  4408. loading=true;
  4409. setTimeout(()=>{loading=false},200);
  4410. }
  4411. }
  4412. if(!isLoading && !stopScroll){
  4413. checkScrollReach();
  4414. }
  4415. if(ruleParser.curSiteRule.lockScroll){
  4416. let curScroll=document.body.scrollTop||document.documentElement.scrollTop;
  4417. if(isLoading && Math.abs(lastScroll-curScroll)>350){
  4418. document.body.scrollTop=lastScroll;
  4419. document.documentElement.scrollTop=lastScroll;
  4420. }else{
  4421. lastScroll=curScroll;
  4422. }
  4423. }
  4424. };
  4425. document.addEventListener('dblclick', e=>{
  4426. if(forceState==1 || e.target.tagName=='INPUT' || e.target.tagName=='TEXTAREA') return;
  4427. if(!rulesData.dbClick2StopKey){
  4428. if((rulesData.dbClick2StopCtrl && !e.ctrlKey) ||
  4429. (rulesData.dbClick2StopAlt && !e.altKey) ||
  4430. (rulesData.dbClick2StopShift && !e.shiftKey) ||
  4431. (rulesData.dbClick2StopMeta && !e.metaKey)){
  4432. return;
  4433. }
  4434. }
  4435. if(e.target.tagName !== "BODY" && e.target.className !== 'pagetual_pageBar'){
  4436. let selStr=document.getSelection().toString();
  4437. if(selStr && selStr.trim()){
  4438. return;
  4439. }
  4440. }
  4441. if(rulesData.dbClick2Stop && (ruleParser.nextLinkHref || loadmoreBtn)){
  4442. setTimeout(()=>{
  4443. if (rulesData.hideBarButNoStop || rulesData.hideBar) {
  4444. changeHideBar(!isHideBar);
  4445. }
  4446. if (!rulesData.hideBarButNoStop) {
  4447. changeStop(!isPause);
  4448. showTips(i18n(isPause?"disable":"enable"));
  4449. }
  4450. if(!isPause){
  4451. checkScrollReach();
  4452. }
  4453. },10);
  4454. }
  4455. });
  4456. if(rulesData.dbClick2StopKey){
  4457. document.addEventListener('keydown', e=>{
  4458. if((rulesData.dbClick2StopCtrl && !e.ctrlKey) ||
  4459. (rulesData.dbClick2StopAlt && !e.altKey) ||
  4460. (rulesData.dbClick2StopShift && !e.shiftKey) ||
  4461. (rulesData.dbClick2StopMeta && !e.metaKey)){
  4462. return;
  4463. }
  4464. if (document.activeElement &&
  4465. (document.activeElement.tagName == 'INPUT' ||
  4466. document.activeElement.tagName == 'TEXTAREA')) {
  4467. return;
  4468. }
  4469. var key = e.key.toLowerCase();
  4470. if(rulesData.dbClick2StopKey.toLowerCase()==key){
  4471. forceState=(forceState==1?0:1);
  4472. showTips(i18n(forceState==1?"disableSiteTips":"enableSiteTips"));
  4473. if(!ruleParser.curSiteRule.url) {
  4474. storage.setItem("forceState_"+location.host, forceState);
  4475. location.reload();
  4476. }
  4477. }
  4478. });
  4479. }
  4480. if (ruleParser.curSiteRule.listenHashChange) {
  4481. window.addEventListener('hashchange', () => {
  4482. urlChanged = true;
  4483. isPause = true;
  4484. if (!ruleParser.nextLinkHref) isLoading = false;
  4485. }, false);
  4486. }
  4487. let manualMode = typeof ruleParser.curSiteRule.manualMode == 'undefined' ? rulesData.manualMode : ruleParser.curSiteRule.manualMode;
  4488. if (manualMode) {
  4489. document.addEventListener('keydown', e => {
  4490. if (document.activeElement &&
  4491. (document.activeElement.tagName == 'INPUT' ||
  4492. document.activeElement.tagName == 'TEXTAREA' ||
  4493. document.activeElement.contentEditable == 'true')) {
  4494. return;
  4495. }
  4496. if(e.keyCode == 39){
  4497. clickNext();
  4498. }
  4499. });
  4500. document.addEventListener('pagetual.next', function() {
  4501. clickNext();
  4502. }, false);
  4503. return;
  4504. }
  4505. if (rulesData.arrowToScroll) {
  4506. let getPageBar = () => {
  4507. let preBar = null, nextBar = null;
  4508. let pageBars = [].slice.call(document.querySelectorAll(".pagetual_pageBar"));
  4509. for (let i = 0; i < pageBars.length; i++) {
  4510. let pageBar = pageBars[i];
  4511. if (!pageBar || !document.body.contains(pageBar)) continue;
  4512. let {
  4513. top,
  4514. right,
  4515. bottom,
  4516. left,
  4517. } = pageBar.getBoundingClientRect();
  4518. if (top > 500) {
  4519. nextBar = pageBar;
  4520. preBar = (i - 1 >= 0 ? pageBars[i - 1] : null);
  4521. if (pageBar && document.body.contains(pageBar)) {
  4522. let {
  4523. top,
  4524. right,
  4525. bottom,
  4526. left,
  4527. } = pageBar.getBoundingClientRect();
  4528. if (top < -500) {
  4529. preBar = pageBar;
  4530. } else preBar = (i - 2 >= 0 ? pageBars[i - 2] : null);
  4531. }
  4532. break;
  4533. }
  4534. }
  4535. if (!nextBar) preBar = pageBars[pageBars.length - 2];
  4536. return {preBar: preBar, nextBar: nextBar};
  4537. };
  4538. document.addEventListener('keyup', e => {
  4539. if (document.activeElement &&
  4540. (document.activeElement.tagName == 'INPUT' ||
  4541. document.activeElement.tagName == 'TEXTAREA' ||
  4542. document.activeElement.contentEditable == 'true')) {
  4543. return;
  4544. }
  4545. if (e.keyCode == 39) {
  4546. let nextPageBar=getPageBar().nextBar;
  4547. if (nextPageBar) {
  4548. scrollToPageBar(nextPageBar);
  4549. } else {
  4550. let scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
  4551. window.scrollTo({ top: scrollTop + (window.innerHeight || document.documentElement.clientHeight), behavior: 'smooth'});
  4552. }
  4553. } else if (e.keyCode == 37) {
  4554. let prePageBar = getPageBar().preBar;
  4555. if (prePageBar) {
  4556. scrollToPageBar(prePageBar);
  4557. } else {
  4558. let scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
  4559. window.scrollTo({ top: scrollTop - (window.innerHeight || document.documentElement.clientHeight), behavior: 'smooth'});
  4560. }
  4561. }
  4562. });
  4563. }
  4564. if (!ruleParser.curSiteRule.wheel) {
  4565. document.addEventListener('scroll', scrollHandler, true);
  4566. }
  4567. document.addEventListener('wheel', scrollHandler, true);
  4568. }
  4569.  
  4570. function showTips(content, wordColor, backColor){
  4571. document.body.appendChild(tipsWords);
  4572. tipsWords.style.opacity=0.8;
  4573. tipsWords.innerText=content;
  4574. tipsWords.style.marginLeft=-tipsWords.offsetWidth/2+"px";
  4575. tipsWords.style.color=wordColor||0xFFFFFF;
  4576. tipsWords.style.backgroundColor=backColor||0x000;
  4577. setTimeout(()=>{tipsWords.style.opacity=0},1000);
  4578. }
  4579.  
  4580. function getLoadMore(doc) {
  4581. if (ruleParser.curSiteRule.loadMore === "") return null;
  4582. let btnSel = ruleParser.curSiteRule.loadMore || ".LoadMore,.load-more,.button-show-more,button[data-testid='more-results-button']", loadmoreBtn;
  4583. if (btnSel) {
  4584. loadmoreBtn = getElement(btnSel, doc);
  4585. }
  4586. if (!loadmoreBtn) {
  4587. let buttons = doc.querySelectorAll("input,button,a,div[onclick]"), loadmoreReg = /^\s*(加载更多|加載更多|load\s*more|もっと読み込む)\s*$/i;
  4588. for (let i = 0; i < buttons.length; i++) {
  4589. let button = buttons[i];
  4590. if (button.innerText.length > 20) continue;
  4591. if (button && loadmoreReg.test(button.innerText)) {
  4592. loadmoreBtn = button;
  4593. break;
  4594. }
  4595. }
  4596. }
  4597. if (loadmoreBtn && !ruleParser.curSiteRule.loadMore && loadmoreBtn.dataset.ajax !== "true") {
  4598. let href = loadmoreBtn.getAttribute("href");
  4599. if (href && href != "/" && !/^(javascript|#)/.test(href.replace(location.href,""))) {
  4600. loadmoreBtn = null;
  4601. }
  4602. }
  4603. return loadmoreBtn;
  4604. }
  4605.  
  4606. function scrollToPageBar(bar){
  4607. let yOffset = -20;
  4608. if (typeof ruleParser.curSiteRule.pageBarTop !== 'undefined') {
  4609. yOffset = -ruleParser.curSiteRule.pageBarTop;
  4610. }
  4611. const y = bar.getBoundingClientRect().top + window.pageYOffset + yOffset;
  4612. window.scrollTo({ top: y, behavior: 'smooth'});
  4613. }
  4614.  
  4615. const pageNumReg=/[&\/\?](p=|page[=\/_-]?)\d+|[_-]\d+\./;
  4616. function createPageBar(url) {
  4617. url = url.replace(/#p{.*/, "");
  4618. if (rulesData.opacity == 0 || ruleParser.curSiteRule.pageBar === 0) return null;
  4619. let insert=ruleParser.getInsert();
  4620. if(!insert || !insert.parentNode)return;
  4621. curPage++;
  4622. let example=ruleParser.curSiteRule.insertPos==2?insert.children[0]:(insert.parentNode.children[parseInt(insert.parentNode.children.length/2)]||insert);
  4623. if (example.className=="pagetual_pageBar") {
  4624. example=example.previousElementSibling;
  4625. }
  4626. if(!example || !example.parentNode)example=insert;
  4627. let exampleStyle = _unsafeWindow.getComputedStyle(example);
  4628. let inTable, inLi;
  4629. if (forceState == 2) {
  4630. inTable = inLi = false;
  4631. } else {
  4632. inTable=example.parentNode.tagName=="TABLE" ||
  4633. example.parentNode.tagName=="TBODY" ||
  4634. example.tagName=="TR" ||
  4635. example.tagName=="TBODY" ||
  4636. exampleStyle.display=="table-row" ||
  4637. (example.previousElementSibling && example.previousElementSibling.tagName=="TR") ||
  4638. (example.previousElementSibling && example.previousElementSibling.tagName=="TBODY");
  4639. inLi=example.tagName=="LI" || (example.previousElementSibling && example.previousElementSibling.tagName=="LI");
  4640. }
  4641. let pageBar=document.createElement(inTable?"tr":(inLi?"li":"div"));
  4642. let upSpan=document.createElement("span");
  4643. let downSpan=document.createElement("span");
  4644. let pageText=document.createElement("a");
  4645. let pageNum;
  4646. let scrollH=Math.max(document.documentElement.scrollHeight, document.body.scrollHeight);
  4647. pageBar.className=isHideBar?"pagetual_pageBar hide":"pagetual_pageBar";
  4648. pageBar.id="pagetual_pageBar"+curPage;
  4649. pageBar.setAttribute("translate", "no");
  4650. if(isPause){
  4651. pageBar.classList.add("stop");
  4652. }
  4653. pageBar.style.cssText=pageBarStyle;
  4654. pageBar.title=i18n(isPause?"enable":"disable");
  4655. upSpan.innerHTML=upSvg;
  4656. upSpan.children[0].style.cssText=upSvgCSS;
  4657. upSpan.title=i18n("toTop");
  4658. downSpan.innerHTML=downSvg;
  4659. downSpan.children[0].style.cssText=downSvgCSS;
  4660. downSpan.title=i18n("toBottom");
  4661. upSpan.style.cssText=initStyle;
  4662. downSpan.style.cssText=initStyle;
  4663. pageText.href=url;
  4664. pageText.style.cssText=pageTextStyle;
  4665. pageText.title=i18n("current");
  4666. if(rulesData.openInNewTab)pageText.target="_blank";
  4667. pageBar.appendChild(upSpan);
  4668. pageBar.appendChild(pageText);
  4669. if(rulesData.pageBarMenu){
  4670. pageText.addEventListener("click", e=>{
  4671. e.stopPropagation();
  4672. if (e.ctrlKey || e.altKey || e.shiftKey || e.metaKey) return;
  4673. e.preventDefault();
  4674. Picker.getInstance().start();
  4675. });
  4676. }
  4677. let touched = false;
  4678. let touchBodyHandler = e => {
  4679. touched = false;
  4680. document.body.removeEventListener('touchstart', touchBodyHandler);
  4681. };
  4682. pageText.addEventListener("touchstart", e => {
  4683. if (touched) return;
  4684. touched = true;
  4685. pageText.style.pointerEvents = 'none';
  4686. setTimeout(() => {
  4687. pageText.style.pointerEvents = 'all';
  4688. }, 250);
  4689. document.body.addEventListener("touchstart", touchBodyHandler);
  4690. });
  4691. if(ruleParser.nextTitle){
  4692. pageText.innerHTML=ruleParser.nextTitle+" ";
  4693. pageText.title=ruleParser.nextTitle;
  4694. }
  4695. if(ruleParser.curSiteRule.pageNum || pageNumReg.test(url)){
  4696. pageText.innerHTML+="Page ";
  4697. pageNum=document.createElement("span");
  4698. pageNum.innerHTML=ruleParser.getPageNumFromUrl(url);
  4699. pageNum.className="pagetual_pageNum";
  4700. pageNum.title=i18n("inputPageNum");
  4701. pageNum.style.cssText=pageTextStyle;
  4702. pageNum.style.cursor="pointer";
  4703. pageNum.style.color="";
  4704. pageNum.style.marginLeft="5px";
  4705. pageNum.addEventListener("click", e=>{
  4706. let pageInput=prompt(i18n("inputPageNum"), "1");
  4707. if(pageInput){
  4708. let pageLink=ruleParser.getLinkByPage(url, pageInput);
  4709. if(pageLink){
  4710. _GM_openInTab(pageLink,{active:true});
  4711. }
  4712. }
  4713. e.preventDefault();
  4714. e.stopPropagation();
  4715. });
  4716. pageBar.appendChild(pageNum);
  4717. }else{
  4718. pageText.innerHTML+="Page "+curPage;
  4719. }
  4720. let preBtn=document.createElement("span");
  4721. preBtn.innerHTML="∧";
  4722. preBtn.title="Prev page";
  4723. preBtn.className="prevScreen";
  4724. 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";
  4725. let nextBtn=document.createElement("span");
  4726. nextBtn.innerHTML="∨";
  4727. nextBtn.title="Next page";
  4728. nextBtn.className="nextScreen";
  4729. 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";
  4730. let localPage=curPage;
  4731. preBtn.addEventListener("click", e=>{
  4732. e.stopPropagation();
  4733. e.preventDefault();
  4734. let prePageBar = document.querySelector("#pagetual_pageBar"+(localPage-1));
  4735. if (prePageBar) {
  4736. scrollToPageBar(prePageBar);
  4737. } else {
  4738. let scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
  4739. window.scrollTo({ top: scrollTop - (window.innerHeight || document.documentElement.clientHeight), behavior: 'smooth'});
  4740. }
  4741. });
  4742. nextBtn.addEventListener("click", e=>{
  4743. e.stopPropagation();
  4744. e.preventDefault();
  4745. let nextPageBar=document.querySelector("#pagetual_pageBar"+(localPage+1));
  4746. if (nextPageBar) {
  4747. scrollToPageBar(nextPageBar);
  4748. } else {
  4749. let nextEle = pageBar.parentNode.children[pageBar.parentNode.children.length - 1];
  4750. if (nextEle) scrollToPageBar(nextEle);
  4751. else {
  4752. scrollH=Math.max(document.documentElement.scrollHeight, document.body.scrollHeight);
  4753. window.scrollTo({ top: scrollH || 9999999, behavior: 'smooth'});
  4754. }
  4755. }
  4756. });
  4757. pageText.insertBefore(preBtn, pageText.firstChild);
  4758. pageText.insertBefore(nextBtn, pageText.firstChild);
  4759. pageBar.appendChild(downSpan);
  4760. if (forceState == 2) {
  4761. pageBar.style.width = "99%";
  4762. } else {
  4763. let parentStyle=_unsafeWindow.getComputedStyle(example.parentNode);
  4764. let parentWidth=example.parentNode.offsetWidth||parseInt(parentStyle.width);
  4765. pageBar.style.width=parentWidth-parseInt(parentStyle.paddingLeft)-parseInt(parentStyle.paddingRight)-10+"px";
  4766. pageBar.style.margin='10px 5px';
  4767. if(parentStyle.display=="grid" || parentStyle.display=="inline-grid"){
  4768. pageBar.style.gridColumnStart=1;
  4769. pageBar.style.gridColumnEnd=1+parseInt(example.parentNode.offsetWidth/example.offsetWidth);
  4770. }
  4771. if(inTable){
  4772. example=(example.tagName=="TR" || example.tagName=="TBODY")?example:example.previousElementSibling;
  4773. if(example.tagName=="TBODY")example=example.querySelector("tr");
  4774. let preTr=example;
  4775. while(preTr && preTr.children.length==0)preTr=preTr.previousElementSibling;
  4776. if(preTr)example=preTr;
  4777. let tdNum=0;
  4778. if (exampleStyle.display=="table-row") {
  4779. [].forEach.call(example.children, el=>{
  4780. tdNum+=el.colSpan||1;
  4781. });
  4782. } else {
  4783. [].forEach.call(example.children, el=>{
  4784. if(el.tagName=="TD" || el.tagName=="TH"){
  4785. tdNum+=el.colSpan||1;
  4786. }
  4787. });
  4788. }
  4789. pageBar.style.display="table-row";
  4790. pageBar.style.backgroundColor="unset";
  4791. pageBar.style.lineHeight="20px";
  4792. pageBar.style.boxShadow="";
  4793. pageBar.style.height="35px";
  4794. let td=document.createElement("td");
  4795. td.colSpan=tdNum||1;
  4796. let inTd=document.createElement("div");
  4797. inTd.style.backgroundColor="rgb(240 240 240 / 80%)";
  4798. inTd.style.borderRadius="20px";
  4799. inTd.style.padding="0 0";
  4800. inTd.style.margin="0";
  4801. inTd.style.lineHeight="20px";
  4802. inTd.style.textAlign="center";
  4803. inTd.style.boxShadow="rgb(0 0 0 / 67%) 0px 0px 10px 0px";
  4804. inTd.appendChild(upSpan);
  4805. inTd.appendChild(pageText);
  4806. if(pageNum)inTd.appendChild(pageNum);
  4807. inTd.appendChild(downSpan);
  4808. td.appendChild(inTd);
  4809. pageBar.appendChild(td);
  4810. }else if(inLi){
  4811. example=example.tagName=="LI"?example:example.previousElementSibling;
  4812. pageBar.style.display=getComputedStyle(example).display;
  4813. pageBar.style.backgroundColor="unset";
  4814. pageBar.style.lineHeight="20px";
  4815. pageBar.style.boxShadow="";
  4816. pageBar.style.height="35px";
  4817. let td=document.createElement("td");
  4818. td.colSpan=example.children.length;
  4819. td.style.width='100%';
  4820. let inTd=document.createElement("div");
  4821. inTd.style.backgroundColor="rgb(240 240 240 / 80%)";
  4822. inTd.style.borderRadius="20px";
  4823. inTd.style.margin="0"
  4824. inTd.style.padding="0 0";
  4825. inTd.style.textAlign="center";
  4826. inTd.style.minWidth="150px";
  4827. inTd.appendChild(upSpan);
  4828. inTd.appendChild(pageText);
  4829. inTd.style.width='calc(100% - 20px)';
  4830. inTd.style.boxShadow="rgb(0 0 0 / 67%) 0px 0px 10px 0px";
  4831. if(pageNum)inTd.appendChild(pageNum);
  4832. inTd.appendChild(downSpan);
  4833. if (pageBar.style.display === 'table-row') {
  4834. td.appendChild(inTd);
  4835. pageBar.appendChild(td);
  4836. } else {
  4837. inTd.style.width='100%';
  4838. pageBar.appendChild(inTd);
  4839. }
  4840. }
  4841. }
  4842.  
  4843. upSpan.addEventListener("click", e=>{
  4844. document.body.scrollTop=0;
  4845. document.documentElement.scrollTop=0;
  4846. e.preventDefault();
  4847. e.stopPropagation();
  4848. });
  4849. downSpan.addEventListener("click", e=>{
  4850. changeStop(true);
  4851. pageBar.title = i18n(isPause ? "enable" : "disable");
  4852. scrollH=Math.max(document.documentElement.scrollHeight, document.body.scrollHeight);
  4853. document.body.scrollTop = scrollH || 9999999;
  4854. document.documentElement.scrollTop = scrollH || 9999999;
  4855. e.preventDefault();
  4856. e.stopPropagation();
  4857. });
  4858. pageBar.addEventListener("click", e=>{
  4859. changeStop(!isPause);
  4860. pageBar.title=i18n(isPause?"enable":"disable");
  4861. });
  4862. ruleParser.insertElement(pageBar);
  4863. if(ruleParser.curSiteRule.pageBar && ruleParser.curSiteRule.pageBar !== 0){
  4864. try{
  4865. ((typeof _unsafeWindow.pagetualPageBar=='undefined') ? Function("pageBar",'"use strict";' + ruleParser.curSiteRule.pageBar) : _unsafeWindow.pagetualPageBar)(pageBar);
  4866. }catch(e){
  4867. debug(e);
  4868. }
  4869. }
  4870.  
  4871. let posEle=pageBar.nextElementSibling||pageBar;
  4872. while(posEle && !posEle.offsetParent){
  4873. posEle=posEle.previousElementSibling||posEle.parentNode;
  4874. }
  4875. if(posEle){
  4876. let actualTop = getElementTop(posEle);
  4877. bottomGap=scrollH-actualTop+(window.innerHeight||document.documentElement.clientHeight)*(ruleParser.curSiteRule.rate||1);
  4878. if(bottomGap<100)bottomGap=100;
  4879. }else{
  4880. bottomGap=1000;
  4881. }
  4882. return pageBar;
  4883. }
  4884.  
  4885. function emuClick(btn){
  4886. let orgHref=btn.getAttribute('href');
  4887. if(orgHref){
  4888. btn.setAttribute('href', orgHref.replace(/#$/,""));
  4889. }
  4890. if(!PointerEvent)return btn.click();
  4891. let eventParam={
  4892. isTrusted: true,
  4893. altKey: false,
  4894. azimuthAngle: 0,
  4895. bubbles: true,
  4896. button: 0,
  4897. buttons: 0,
  4898. clientX: 1,
  4899. clientY: 1,
  4900. cancelBubble: false,
  4901. cancelable: true,
  4902. composed: true,
  4903. ctrlKey: false,
  4904. defaultPrevented: false,
  4905. detail: 1,
  4906. eventPhase: 2,
  4907. fromElement: null,
  4908. height: 1,
  4909. isPrimary: false,
  4910. metaKey: false,
  4911. pointerId: 1,
  4912. pointerType: "mouse",
  4913. pressure: 0,
  4914. relatedTarget: null,
  4915. returnValue: true,
  4916. shiftKey: false,
  4917. toElement: null,
  4918. twist: 0,
  4919. which: 1
  4920. };
  4921. let mouseEvent = new PointerEvent("mousedown",eventParam);
  4922. btn.dispatchEvent(mouseEvent);
  4923. mouseEvent = new PointerEvent("mouseup",eventParam);
  4924. btn.dispatchEvent(mouseEvent);
  4925. let dispatchTouchEvent = (ele, type) => {
  4926. let touchEvent;
  4927. try {
  4928. touchEvent = document.createEvent('TouchEvent')
  4929. touchEvent.initTouchEvent(type, true, true)
  4930. } catch (err) {
  4931. try {
  4932. touchEvent = document.createEvent('UIEvent')
  4933. touchEvent.initUIEvent(type, true, true)
  4934. } catch (err) {
  4935. touchEvent = document.createEvent('Event')
  4936. touchEvent.initEvent(type, true, true)
  4937. }
  4938. }
  4939. touchEvent.targetTouches = [{
  4940. pageX: 1,
  4941. pageY: 1,
  4942. clientX: 1,
  4943. clientY: 1,
  4944. target: btn
  4945. }];
  4946. touchEvent.touches = [{
  4947. pageX: 1,
  4948. pageY: 1,
  4949. clientX: 1,
  4950. clientY: 1,
  4951. target: btn
  4952. }];
  4953. touchEvent.changedTouches = [{
  4954. pageX: 1,
  4955. pageY: 1,
  4956. clientX: 1,
  4957. clientY: 1,
  4958. target: btn
  4959. }];
  4960. ele.dispatchEvent(touchEvent);
  4961. }
  4962. dispatchTouchEvent(btn, "touchstart");
  4963. dispatchTouchEvent(btn, "touchend");
  4964.  
  4965. btn.click();
  4966. if(orgHref){
  4967. setTimeout(()=>btn.setAttribute('href', orgHref),0);
  4968. }
  4969. }
  4970.  
  4971. var failFromIframe=0;
  4972. var inCors=false;
  4973. var checkRemoveIntv;
  4974. function requestFromIframe(url, callback){
  4975. url = url.indexOf('=') == -1 ? url.replace(/#[^#]*/,"") : url;
  4976. let iframe = document.createElement('iframe');
  4977. iframe.name = 'pagetual-iframe';
  4978. iframe.width = '100%';
  4979. iframe.height = '1000';
  4980. iframe.frameBorder = '0';
  4981. if(ruleParser.curSiteRule.sandbox!=false){
  4982. iframe.sandbox="allow-same-origin allow-scripts allow-popups allow-forms";
  4983. }
  4984. 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;';
  4985. let waitTime=100,checkEval;
  4986. if(ruleParser.curSiteRule.waitElement){
  4987. checkEval = doc => {
  4988. return ruleParser.waitElement(doc);
  4989. };
  4990. }else if(ruleParser.curSiteRule.wait){
  4991. if(isNaN(ruleParser.curSiteRule.wait)){
  4992. try{
  4993. checkEval=(typeof _unsafeWindow.pagetualWait=='undefined') ? Function("doc",'"use strict";' + ruleParser.curSiteRule.wait) : _unsafeWindow.pagetualWait;
  4994. }catch(e){
  4995. debug(e);
  4996. }
  4997. }else{
  4998. waitTime=ruleParser.curSiteRule.wait;
  4999. }
  5000. }
  5001. if (checkRemoveIntv) clearInterval(checkRemoveIntv);
  5002. checkRemoveIntv = setInterval(() => {
  5003. if (!iframe || !document.body.contains(iframe)) {
  5004. clearInterval(checkRemoveIntv);
  5005. loadPageOver();
  5006. }
  5007. }, 500);
  5008. let loadedHandler = e => {
  5009. if(e.data != 'pagetual-iframe:DOMLoaded' && e.type != 'load')return;
  5010. clearInterval(checkRemoveIntv);
  5011. window.removeEventListener('message', loadedHandler, false);
  5012. iframe.removeEventListener('load', loadedHandler, false);
  5013. let tryTimes=0;
  5014. function checkIframe(){
  5015. if (urlChanged || isPause) {
  5016. return callback(false, false);
  5017. }
  5018. try{
  5019. let doc=iframe.contentDocument || iframe.contentWindow.document;
  5020. let base=doc.querySelector("base");
  5021. ruleParser.basePath=base?base.href:url;
  5022. let eles=ruleParser.getPageElement(doc, iframe.contentWindow);
  5023. if(checkEval && !checkEval(doc)){
  5024. setTimeout(()=>{
  5025. checkIframe();
  5026. },waitTime);
  5027. return;
  5028. }else if(eles && eles.length>0){
  5029. callback(doc, eles);
  5030. }else if(tryTimes++ < 100){
  5031. setTimeout(()=>{
  5032. checkIframe();
  5033. },waitTime);
  5034. return;
  5035. }else{
  5036. if(failFromIframe++ > 2){
  5037. failFromIframe=0;
  5038. debug("Stop as failFromIframe");
  5039. isPause=true;
  5040. callback(false, false);
  5041. }else{
  5042. callback(false, false);
  5043. }
  5044. }
  5045. }catch(e){
  5046. debug("Stop as cors");
  5047. inCors=true;
  5048. if (forceState === 3) {
  5049. isPause=true;
  5050. }
  5051. if(!ruleParser.curSiteRule.pageElement){
  5052. ruleParser.curSiteRule.pageElement=allOfBody;
  5053. ruleParser.getInsert(true);
  5054. }
  5055. ruleParser.curSiteRule.action=0;
  5056. ruleParser.nextLinkHref=url;
  5057. callback(false, false);
  5058. nextPage();
  5059. }
  5060. document.body.removeChild(iframe);
  5061. }
  5062. setTimeout(()=>{
  5063. checkIframe();
  5064. },waitTime);
  5065. };
  5066. window.addEventListener('message', loadedHandler, false);
  5067. iframe.addEventListener('load', loadedHandler, false);
  5068. iframe.src=url;
  5069. document.body.appendChild(iframe);
  5070. }
  5071.  
  5072. var emuIframe,lastActiveUrl;
  5073. function emuPage(callback){
  5074. let orgPage=null,orgContent=null,preContent=null,iframeDoc,times=0,loadmoreBtn,pageEle,nextLink,loadmoreEnd=false,waitTimes=10,changed=false;
  5075. function returnFalse(log){
  5076. debug(log);
  5077. isPause=true;
  5078. callback(false, false);
  5079. if(emuIframe && emuIframe.parentNode){
  5080. emuIframe.parentNode.removeChild(emuIframe);
  5081. emuIframe=null;
  5082. }
  5083. }
  5084. async function checkPage(){
  5085. if(isPause)return loadPageOver();
  5086. try{
  5087. iframeDoc=emuIframe.contentDocument || emuIframe.contentWindow.document;
  5088. }catch(e){
  5089. returnFalse("Stop as cors");
  5090. return;
  5091. }
  5092.  
  5093. let waitTime=200,checkEval;
  5094. if(ruleParser.curSiteRule.waitElement){
  5095. checkEval = doc => {
  5096. return ruleParser.waitElement(doc);
  5097. };
  5098. }else if(ruleParser.curSiteRule.wait){
  5099. if(isNaN(ruleParser.curSiteRule.wait)){
  5100. try{
  5101. checkEval=(typeof _unsafeWindow.pagetualWait=='undefined') ? Function("doc", '"use strict";' + ruleParser.curSiteRule.wait) : _unsafeWindow.pagetualWait;
  5102. }catch(e){
  5103. debug(e);
  5104. }
  5105. }else{
  5106. waitTime=ruleParser.curSiteRule.wait;
  5107. }
  5108. }
  5109.  
  5110. if(!orgPage){
  5111. if(!loadmoreEnd){
  5112. loadmoreBtn=getLoadMore(iframeDoc);
  5113. if(loadmoreBtn && isVisible(loadmoreBtn, iframeDoc.defaultView)){
  5114. emuClick(loadmoreBtn);
  5115. let intv=setInterval(()=>{
  5116. loadmoreBtn=getLoadMore(iframeDoc);
  5117. if(!loadmoreBtn || !document.body.contains(loadmoreBtn) || !isVisible(loadmoreBtn, iframeDoc.defaultView)){
  5118. clearInterval(intv);
  5119. loadmoreEnd=true;
  5120. setTimeout(()=>{
  5121. checkPage();
  5122. },500);
  5123. }else if(isInViewPort(loadmoreBtn)){
  5124. emuClick(loadmoreBtn);
  5125. }
  5126. },200);
  5127. return;
  5128. }else{
  5129. loadmoreEnd=true;
  5130. }
  5131. }
  5132. if(checkEval && !checkEval(iframeDoc)){
  5133. waitTimes=10;
  5134. setTimeout(()=>{
  5135. checkPage();
  5136. },waitTime);
  5137. return;
  5138. }else {
  5139. nextLink = await ruleParser.getNextLink(iframeDoc);
  5140. pageEle = ruleParser.getPageElement(iframeDoc, iframeDoc.defaultView, true);
  5141. if (!pageEle || pageEle.length==0 || !nextLink) {
  5142. if (waitTimes-- > 0) {
  5143. setTimeout(() => {
  5144. checkPage();
  5145. }, waitTime);
  5146. return;
  5147. }
  5148. }
  5149. }
  5150. orgPage=pageEle;
  5151. if(!orgPage || orgPage.length==0){
  5152. returnFalse("Stop as no page when emu");
  5153. return;
  5154. }
  5155. if(orgPage[0].tagName=="UL")orgPage=orgPage[0].children;
  5156. if(nextLink){
  5157. orgPage=orgPage[parseInt(orgPage.length/2)];
  5158. if(orgPage.tagName=="IMG"){
  5159. if (!ruleParser.curSiteRule.lazyImgSrc) ruleParser.curSiteRule.lazyImgSrc = "0";
  5160. if (orgPage.src) {
  5161. orgContent = orgPage.src;
  5162. } else {
  5163. setTimeout(()=>{
  5164. checkPage();
  5165. },500);
  5166. return;
  5167. }
  5168. }else{
  5169. orgContent=orgPage.innerHTML;
  5170. }
  5171. preContent=orgContent;
  5172. if(!isVisible(nextLink, iframeDoc.defaultView)){
  5173. returnFalse("Stop as next hide when emu");
  5174. }else{
  5175. emuClick(nextLink);
  5176. setTimeout(()=>{
  5177. checkPage();
  5178. },500);
  5179. }
  5180. }else{
  5181. returnFalse("Stop as no next when emu");
  5182. }
  5183. return;
  5184. }
  5185. nextLink = nextLink || await ruleParser.getNextLink(iframeDoc);
  5186. if(!nextLink){
  5187. if(waitTimes-->0){
  5188. setTimeout(()=>{
  5189. checkPage();
  5190. },waitTime);
  5191. return;
  5192. }
  5193. }
  5194. if(times++ > 100){
  5195. returnFalse("Stop as timeout when emu");
  5196. return;
  5197. }
  5198. let eles=ruleParser.getPageElement(iframeDoc, iframeDoc.defaultView, true),checkItem;
  5199. if(eles && eles.length>0){
  5200. checkItem=eles;
  5201. if(eles[0].tagName=="UL")checkItem=eles[0].children;
  5202. checkItem=checkItem[parseInt(checkItem.length/2)];
  5203. }
  5204. if(!checkItem || (checkEval && !checkEval(iframeDoc))){
  5205. setTimeout(()=>{
  5206. checkPage();
  5207. },waitTime);
  5208. }else{
  5209. let checkInner;
  5210. if (checkItem.tagName == "IMG") {
  5211. if (checkItem.src) {
  5212. checkInner = checkItem.src;
  5213. } else {
  5214. setTimeout(() => {
  5215. checkPage();
  5216. }, waitTime);
  5217. return;
  5218. }
  5219. }else{
  5220. checkInner=checkItem.innerHTML;
  5221. }
  5222. if(orgPage!=checkItem || checkInner!=preContent){
  5223. changed=true;
  5224. orgPage=checkItem;
  5225. preContent=checkInner;
  5226. setTimeout(()=>{
  5227. checkPage();
  5228. },waitTime);
  5229. }else if(changed){
  5230. times = 0;
  5231. if (orgContent == preContent) {
  5232. returnFalse("Stop as same content");
  5233. } else {
  5234. callback(iframeDoc, eles);
  5235. }
  5236. }else{
  5237. if (times % 5 === 1) {
  5238. emuClick(nextLink);
  5239. }
  5240. setTimeout(()=>{
  5241. checkPage();
  5242. },waitTime);
  5243. }
  5244. }
  5245. }
  5246. if(!emuIframe){
  5247. let loaded=false;
  5248. emuIframe = document.createElement('iframe');
  5249. emuIframe.name = 'pagetual-iframe';
  5250. if(ruleParser.curSiteRule.sandbox!=false){
  5251. emuIframe.sandbox="allow-same-origin allow-scripts allow-popups allow-forms";
  5252. }
  5253. emuIframe.width = '100%';
  5254. emuIframe.height = '100';
  5255. emuIframe.frameBorder = '0';
  5256. 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;';
  5257. emuIframe.addEventListener("load", e => {
  5258. setTimeout(() => {
  5259. try {
  5260. iframeDoc = emuIframe.contentDocument || emuIframe.contentWindow.document;
  5261. } catch(e) {
  5262. returnFalse("Stop as cors");
  5263. return;
  5264. }
  5265. let code = ruleParser.curSiteRule.init;
  5266. if (code) {
  5267. try {
  5268. Function('doc','win','iframe','"use strict";' + code)(iframeDoc, iframeDoc.defaultView, emuIframe);
  5269. } catch(e) {
  5270. debug(e);
  5271. }
  5272. }
  5273. if (loaded) return;
  5274. loaded = true;
  5275. checkPage();
  5276. },500);
  5277. });
  5278. if (!lastActiveUrl) lastActiveUrl=location.href;
  5279. emuIframe.src = lastActiveUrl;
  5280. document.body.appendChild(emuIframe);
  5281. }else{
  5282. if (emuIframe.src != lastActiveUrl) emuIframe.src = lastActiveUrl;
  5283. checkPage();
  5284. }
  5285. }
  5286.  
  5287. var scrollToResizeInited = false;
  5288. var resizePool = [];
  5289. var scrollingToResize = false;
  5290.  
  5291. function scrollToResize(e) {
  5292. if (scrollingToResize) return;
  5293. else {
  5294. scrollingToResize = true;
  5295. let fitWidth = ruleParser.curSiteRule.fitWidth !== false;
  5296. let resizeHandler = () => {
  5297. resizePool.forEach(resizeArr => {
  5298. let iframe = resizeArr[1]();
  5299. let frameDoc = resizeArr[2]();
  5300. if(ruleParser.curSiteRule.singleUrl || forceState === 2){
  5301. iframe.style.height = (frameDoc.body.scrollHeight || frameDoc.body.offsetHeight) + "px";
  5302. iframe.style.minHeight = iframe.style.height;
  5303. iframe.style.width = "100%";
  5304. frameDoc.documentElement.scrollTop = 0;
  5305. frameDoc.documentElement.scrollLeft = 0;
  5306. }else{
  5307. let pageEle = resizeArr[0]();
  5308. if(pageEle){
  5309. let targetElement = pageEle[0];
  5310. if (!targetElement) return;
  5311. if(pageEle.length > 1){
  5312. targetElement = targetElement.parentNode;
  5313. }
  5314. let scrollHeight = targetElement.scrollHeight || targetElement.offsetHeight;
  5315. if(parseInt(iframe.style.height)==scrollHeight) return;
  5316. iframe.style.height=(scrollHeight+1)+"px";
  5317. let scrollTop = 0, scrollLeft = 0;
  5318. frameDoc.body.scrollTop = 0;
  5319. frameDoc.body.scrollLeft = 0;
  5320. while(targetElement && targetElement.offsetParent){
  5321. targetElement.offsetParent.scrollTop = targetElement.offsetTop;
  5322. if(targetElement.offsetParent.scrollTop == 0){
  5323. scrollTop += targetElement.offsetTop;
  5324. }
  5325. if(fitWidth){
  5326. targetElement.offsetParent.scrollLeft = targetElement.offsetLeft;
  5327. if(targetElement.offsetParent.scrollLeft == 0){
  5328. scrollLeft += targetElement.offsetLeft;
  5329. }
  5330. }
  5331. targetElement = targetElement.offsetParent;
  5332. }
  5333. frameDoc.documentElement.scrollTop = scrollTop;
  5334. frameDoc.documentElement.scrollLeft = scrollLeft;
  5335. if (frameDoc.documentElement.scrollTop == 0 && frameDoc.documentElement.scrollLeft == 0) {
  5336. frameDoc.body.scrollTop += scrollTop;
  5337. frameDoc.body.scrollLeft += scrollLeft;
  5338. }
  5339. if(!fitWidth && iframe.style.marginLeft == '0px'){
  5340. iframe.style.width = "100vw";
  5341. iframe.style.marginLeft = -iframe.getBoundingClientRect().left + "px";
  5342. }
  5343. }
  5344. }
  5345. });
  5346. };
  5347. setTimeout(() => {
  5348. scrollingToResize = false;
  5349. resizeHandler();
  5350. }, 200);
  5351. resizeHandler();
  5352. }
  5353. }
  5354.  
  5355. function forceIframe(url, callback){
  5356. url = url.indexOf('=') == -1 ? url.replace(/#[^#]*/,"") : url;
  5357. let curIframe = document.createElement('iframe'),iframeDoc,isloaded=false,inAction=true;
  5358. let loadedHandler = ()=>{
  5359. inAction=false;
  5360. if(isloaded)return;
  5361. isloaded=true;
  5362. ruleParser.insertPage(iframeDoc, [], url, null, true);
  5363. callback(curIframe, true);
  5364. let getIframe = () => {
  5365. return curIframe;
  5366. };
  5367. let getFrameDoc = () => {
  5368. return iframeDoc;
  5369. };
  5370. if(ruleParser.curSiteRule.singleUrl){
  5371. resizePool.push([() => {}, getIframe, getFrameDoc]);
  5372. }else{
  5373. let pageElement = ruleParser.getPageElement(iframeDoc,iframeDoc.defaultView);
  5374. let getPageEle = () => {
  5375. if (!pageElement || pageElement.length===0) {
  5376. pageElement = ruleParser.getPageElement(iframeDoc,iframeDoc.defaultView);
  5377. }
  5378. return pageElement;
  5379. };
  5380. resizePool.push([getPageEle, getIframe, getFrameDoc]);
  5381. }
  5382. scrollToResize();
  5383. };
  5384. curIframe.name = 'pagetual-iframe';
  5385. curIframe.sandbox="allow-same-origin allow-scripts allow-popups allow-forms";
  5386. curIframe.frameBorder = '0';
  5387. curIframe.scrolling="no";
  5388. 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;';
  5389. curIframe.addEventListener("load", e=>{
  5390. try{
  5391. iframeDoc=curIframe.contentDocument || curIframe.contentWindow.document;
  5392. }catch(e){
  5393. debug("Stop as cors");
  5394. isPause=true;
  5395. callback(false, false);
  5396. return;
  5397. }
  5398. let css=ruleParser.curSiteRule.css || rulesData.customCss;
  5399. if(css){
  5400. css = css.replace(/^inIframe:/, "");
  5401. let styleEle=iframeDoc.createElement("style");
  5402. styleEle.innerHTML=css;
  5403. iframeDoc.head.appendChild(styleEle);
  5404. }
  5405. loadedHandler();
  5406. let code=ruleParser.curSiteRule.init;
  5407. if(code){
  5408. try{
  5409. Function('doc','win','iframe','"use strict";' + code)(iframeDoc,iframeDoc.defaultView,curIframe);
  5410. }catch(e){
  5411. debug(e);
  5412. }
  5413. }
  5414. });
  5415. let checkTimes=0,findPageEle=false;
  5416. let forceRefresh=e=>{
  5417. if(inAction || !iframeDoc)return;
  5418. inAction=true;
  5419. let foundNext=()=>{
  5420. document.removeEventListener("scroll", forceRefresh);
  5421. }
  5422. setTimeout(async () => {
  5423. inAction=false;
  5424. if(!ruleParser.nextLinkHref){
  5425. checkTimes++;
  5426. await ruleParser.getNextLink(iframeDoc);
  5427. if(ruleParser.nextLinkHref){
  5428. foundNext();
  5429. }else if(checkTimes>=10){
  5430. foundNext();
  5431. }else if(checkTimes>=3 && !findPageEle){
  5432. let pageElement = ruleParser.getPageElement(iframeDoc,iframeDoc.defaultView);
  5433. if(!pageElement){
  5434. inAction=true;
  5435. curIframe.contentWindow.location.reload();
  5436. }else{
  5437. findPageEle=true;
  5438. }
  5439. }
  5440. }else{
  5441. foundNext();
  5442. }
  5443. },50);
  5444. };
  5445. document.addEventListener("scroll", forceRefresh);
  5446. curIframe.src=url;
  5447. let insert=ruleParser.getInsert();
  5448. if(ruleParser.curSiteRule.singleUrl || forceState==2){
  5449. document.body.appendChild(loadingDiv);
  5450. document.body.appendChild(curIframe);
  5451. }else{
  5452. ruleParser.insertElement(curIframe);
  5453. }
  5454.  
  5455. if (!scrollToResizeInited) {
  5456. scrollToResizeInited = true;
  5457. document.addEventListener("scroll", scrollToResize);
  5458. }
  5459. return curIframe;
  5460. }
  5461.  
  5462. function loadPageOver(){
  5463. isLoading = false;
  5464. stopScroll = true;
  5465. setTimeout(() => {stopScroll = false}, 500);
  5466. if(loadingDiv.parentNode){
  5467. loadingDiv.parentNode.removeChild(loadingDiv);
  5468. }
  5469. }
  5470.  
  5471. var tryTimes = 0;
  5472.  
  5473. async function nextPage(){
  5474. if(typeof ruleParser.curSiteRule.manualMode=='undefined' ? rulesData.manualMode : ruleParser.curSiteRule.manualMode)return;
  5475. if(typeof ruleParser.curSiteRule.clickMode=='undefined' ? rulesData.clickMode : ruleParser.curSiteRule.clickMode)return;
  5476. if(isPause || isLoading || forceState==1)return;
  5477. if(ruleParser.curSiteRule.delay){
  5478. try{
  5479. let checkDelay=((typeof _unsafeWindow.pagetualDelay=='undefined') ? Function('"use strict";' + ruleParser.curSiteRule.delay) : _unsafeWindow.pagetualDelay)();
  5480. if(!checkDelay)return;
  5481. }catch(e){
  5482. debug(e);
  5483. }
  5484. }
  5485. if(ruleParser.curSiteRule.pageElementCss || ruleParser.curSiteRule.pageElementStyle || rulesData.pageElementCss){
  5486. ruleParser.getPageElement(document, _unsafeWindow);
  5487. }
  5488. let nextLink = ruleParser.nextLinkHref;
  5489. if (!nextLink) {
  5490. if (curPage == 1) {
  5491. await ruleParser.getNextLink(document);
  5492. nextLink = ruleParser.nextLinkHref;
  5493. }
  5494. if (!nextLink) {
  5495. isLoading = true;
  5496. if (curPage == 1 && (ruleParser.curSiteRule.pinUrl || tryTimes++ <= 10)) {
  5497. setTimeout(() => {isLoading = false}, 500);
  5498. }
  5499. return;
  5500. }
  5501. }
  5502. let pvGallery=document.querySelector("span.pv-gallery-container");
  5503. if(pvGallery && pvGallery.style.display!="none")return;
  5504. let insert=ruleParser.getInsert();
  5505. if (insert) {
  5506. if (curPage == 1) {
  5507. /*window.postMessage({
  5508. insert: geneSelector(ruleParser.curSiteRule.insertPos == 2 ? insert : insert.parentNode, true),
  5509. command: 'pagetual.insert'
  5510. }, '*');*/
  5511. }
  5512. let isJs = ruleParser.curSiteRule.action == 3 || /^(javascript|#)/.test(nextLink.replace(location.href,""));
  5513. if(!isJs){
  5514. emuIframe=null;
  5515. lastActiveUrl=nextLink;
  5516. if(location.protocol=="https:" && /^http:/.test(nextLink)){
  5517. nextLink=nextLink.replace(/^http/,"https");
  5518. }
  5519. }
  5520. isLoading=true;
  5521. ruleParser.insertElement(loadingDiv);
  5522. let parent=loadingDiv.parentNode;
  5523. if(parent.tagName=="TBODY"){
  5524. parent=parent.parentNode;
  5525. }
  5526. if(parent.tagName=="TABLE"){
  5527. parent.parentNode.appendChild(loadingDiv);
  5528. }
  5529. loadingDiv.style.cssText=loadingCSS;
  5530. let sleep=ruleParser.curSiteRule.sleep||0;
  5531. setTimeout(()=>{
  5532. if(ruleParser.curSiteRule.pageElementByJs){
  5533. var over=ele=>{
  5534. loadPageOver();
  5535. if (urlChanged || isPause) return;
  5536. if (ele) {
  5537. createPageBar(nextLink);
  5538. ruleParser.insertPage(null, ele, nextLink, null, true);
  5539. if(autoLoadNum>=0){
  5540. if(autoLoadNum!=0 && --autoLoadNum==0){
  5541. autoLoadNum=-1;
  5542. }else{
  5543. setTimeout(() => nextPage(), 1);
  5544. }
  5545. }
  5546. }else{
  5547. debug("Stop as no page when get by js");
  5548. isPause=true;
  5549. }
  5550. };
  5551. try{
  5552. ((typeof _unsafeWindow.pagetualPageElementByJs=='undefined') ? Function("over",'"use strict";' + ruleParser.curSiteRule.pageElementByJs) : _unsafeWindow.pagetualPageElementByJs)(over);
  5553. }catch(e){
  5554. debug(e);
  5555. }
  5556. }else if((forceState==2||ruleParser.curSiteRule.action==2) && !isJs){
  5557. forceIframe(nextLink, (iframe, eles)=>{
  5558. loadPageOver();
  5559. if (urlChanged || isPause) return;
  5560. let pageBar = createPageBar(nextLink);
  5561. if (pageBar) iframe.parentNode.insertBefore(pageBar, iframe);
  5562. if (autoLoadNum >= 0) {
  5563. if (autoLoadNum != 0 && --autoLoadNum == 0) {
  5564. autoLoadNum=-1;
  5565. } else {
  5566. setTimeout(() => nextPage(), 1);
  5567. }
  5568. }
  5569. });
  5570. }else if((forceState==3||ruleParser.curSiteRule.action==1) && !isJs){
  5571. requestFromIframe(nextLink, (doc, eles)=>{
  5572. loadPageOver();
  5573. if (urlChanged || isPause) return;
  5574. if (eles) {
  5575. ruleParser.insertPage(doc, eles, nextLink, ()=>{
  5576. createPageBar(nextLink);
  5577. }, true);
  5578. if(autoLoadNum>=0){
  5579. if(autoLoadNum!=0 && --autoLoadNum==0){
  5580. autoLoadNum=-1;
  5581. }else{
  5582. setTimeout(() => nextPage(), 1);
  5583. }
  5584. }
  5585. }
  5586. });
  5587. }else{
  5588. if(!isJs){
  5589. requestDoc(nextLink, (eles)=>{
  5590. loadPageOver();
  5591. if (urlChanged || isPause) return;
  5592. if (eles) {
  5593. createPageBar(nextLink);
  5594. if(autoLoadNum>=0){
  5595. if(autoLoadNum!=0 && --autoLoadNum==0){
  5596. autoLoadNum=-1;
  5597. }else{
  5598. setTimeout(() => nextPage(), 1);
  5599. }
  5600. }
  5601. }
  5602. });
  5603. }else{
  5604. emuPage((doc, eles)=>{
  5605. loadPageOver();
  5606. if (urlChanged || isPause) return;
  5607. if (eles) {
  5608. ruleParser.insertPage(doc, eles, "", ()=>{
  5609. createPageBar(nextLink);
  5610. }, true);
  5611. if(autoLoadNum>=0){
  5612. if(autoLoadNum!=0 && --autoLoadNum==0){
  5613. autoLoadNum=-1;
  5614. }else{
  5615. setTimeout(() => nextPage(), 1);
  5616. }
  5617. }
  5618. }
  5619. });
  5620. }
  5621. }
  5622. },sleep);
  5623. }
  5624. }
  5625.  
  5626. function init(){
  5627. initRules(()=>{
  5628. initPage();
  5629. });
  5630. }
  5631.  
  5632. function visibilitychangeHandler(){
  5633. document.removeEventListener('visibilitychange', visibilitychangeHandler);
  5634. init();
  5635. }
  5636.  
  5637. setTimeout(()=>{
  5638. if (document.hidden) {
  5639. document.addEventListener('visibilitychange', visibilitychangeHandler);
  5640. } else {
  5641. init();
  5642. }
  5643. },100);
  5644. })();