东方永页机

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

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

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

QingJ © 2025

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