东方永页机

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

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

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