东方永页机

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

当前为 2022-10-18 提交的版本,查看 最新版本

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

QingJ © 2025

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