东方永页机

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

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

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