东方永页机

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

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

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