东方永页机

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

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

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