东方永页机

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

当前为 2023-02-04 提交的版本,查看 最新版本

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

QingJ © 2025

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