东方永页机

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

目前为 2022-10-15 提交的版本,查看 最新版本

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