东方永页机

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

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

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