东方永页机

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

目前为 2023-02-16 提交的版本,查看 最新版本

  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.61
  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% - 75px);
  2526. left: calc(99% - 60px);
  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 / windowWidth * 100;
  2645. initY = e.clientY / windowHeight * 100;
  2646. this.frame.style.top = `calc(${initY}% - 80px)`;
  2647. this.frame.style.left = `calc(${initX}% - 5px)`;
  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}% - 80px)`;
  2672. this.frame.style.left = `calc(${rulesData.sideControllerPos.x}% - 5px)`;
  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. }
  2875. #pagetual-picker>.title {
  2876. margin: -5px 45px 10px 45px;
  2877. font-size: 20px;
  2878. font-weight: bold;
  2879. cursor: move;
  2880. border-bottom: 1px solid black;
  2881. user-select: none;
  2882. color: orangered;
  2883. font-family: Times New Roman;
  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. }
  2925. #pagetual-picker textarea:focus {
  2926. color: #495057;
  2927. background-color: #fff;
  2928. border-color: #80bdff;
  2929. outline: 0;
  2930. box-shadow: 0 0 0 3.2px rgb(0 123 255 / 25%);
  2931. }
  2932. #pagetual-picker [type=checkbox],
  2933. #pagetual-picker [type=radio] {
  2934. line-height: 20px;
  2935. height: 25px;
  2936. width: 25px;
  2937. margin-left: 5px;
  2938. vertical-align: middle;
  2939. appearance: auto;
  2940. display: inline-block;
  2941. }
  2942. #pagetual-picker label {
  2943. font-size: 18px;
  2944. line-height: 25px;
  2945. vertical-align: middle;
  2946. display: inline-block;
  2947. color: black;
  2948. }
  2949. #pagetual-picker .bottom {
  2950. text-align: left;
  2951. margin: 10px 0;
  2952. width: 100%;
  2953. }
  2954. #pagetual-picker .bottom>button {
  2955. float: right;
  2956. }
  2957. #pagetual-picker svg {
  2958. width: 30px;
  2959. height: 30px;
  2960. vertical-align: middle;
  2961. fill: #161616;
  2962. overflow: hidden;
  2963. }
  2964. #pagetual-picker .allpath {
  2965. font-size: 18px;
  2966. margin: 10px;
  2967. max-width: 330px;
  2968. word-break: break-all;
  2969. cursor: context-menu;
  2970. overflow: hidden;
  2971. max-height: 42px;
  2972. -moz-transition:max-height 1s ease-in;
  2973. -webkit-transition:max-height 1s ease-in;
  2974. transition:max-height 1s ease-in;
  2975. color: black;
  2976. }
  2977. #pagetual-picker .allpath:hover {
  2978. max-height: calc(100vh - 130px);
  2979. overflow: auto;
  2980. }
  2981. #pagetual-picker .allpath>span.path {
  2982. cursor: pointer;
  2983. }
  2984. #pagetual-picker .allpath>span.path:hover {
  2985. color: orangered;
  2986. }
  2987. #pagetual-picker .moreConfig {
  2988. display: flex;
  2989. justify-content: space-between;
  2990. border-top: 1px solid;
  2991. padding-top: 10px;
  2992. width: 100%;
  2993. }
  2994. #pagetual-picker .command {
  2995. width: 100%;
  2996. color: black!important;
  2997. text-align: center;
  2998. font-size: large;
  2999. margin-top: 10px;
  3000. }
  3001. #pagetual-picker .command:hover {
  3002. color: orangered;
  3003. }
  3004. #pagetual-picker #showDetail {
  3005. float: initial;
  3006. margin-top: 10px;
  3007. }
  3008. #pagetual-picker #showDetail.showDetail {
  3009. float: right;
  3010. }
  3011. #pagetual-picker #showDetail>svg {
  3012. -moz-transition:transform 0.3s ease;
  3013. -webkit-transition:transform 0.3s ease;
  3014. transition:transform 0.3 ease;
  3015. }
  3016. #pagetual-picker #showDetail.showDetail>svg {
  3017. transform: rotate(180deg);
  3018. }
  3019. #pagetual-picker .tempRule {
  3020. margin-top: 10px;
  3021. height: 300px;
  3022. }
  3023. #pagetual-picker #saveDetail {
  3024. display: none;
  3025. position: absolute;
  3026. bottom: 10px;
  3027. right: 8px;
  3028. }
  3029. #pagetual-picker .showDetail~#saveDetail {
  3030. display: inline-block;
  3031. }
  3032. #pagetual-picker #saveDetail svg {
  3033. width: 35px;
  3034. height: 35px;
  3035. }
  3036. `;
  3037. this.styleEle = _GM_addStyle(this.cssText);
  3038. this.mainSignDiv = this.createSignDiv();
  3039. this.allSignDiv = [];
  3040. let frame = document.createElement("div");
  3041. frame.id = "pagetual-picker";
  3042. frame.innerHTML = createHTML(`
  3043. <button title="Pagetual" type="button" class="logoToHome">
  3044. <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>
  3045. </button>
  3046. <div class="title">${i18n("picker")}</div>
  3047. <button title="${i18n("closePicker")}" type="button" class="closePicker">
  3048. <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>
  3049. </button>
  3050. <div class="allpath" title="${i18n("switchSelector")}"></div>
  3051. <div>
  3052. <textarea class="selector" spellcheck="false" name="selector" placeholder="${i18n("pickerPlaceholder")}"></textarea>
  3053. <button id="check" title="${i18n("pickerCheck")}" type="button">
  3054. <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>
  3055. </button>
  3056. </div>
  3057. <div class="bottom">
  3058. <input name="xpath" id="checkbox_id" type="checkbox">
  3059. <label for="checkbox_id">XPath</label>
  3060. <button id="edit" title="${i18n("gotoEdit")}" type="button">
  3061. <svg viewBox="0 0 1024 1024" style="color: orangered;fill: orangered;">
  3062. <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">
  3063. </path>
  3064. </svg>
  3065. </button>
  3066. </div>
  3067. <div class="moreConfig">
  3068. <div title="${i18n('forceStateIframe')}">
  3069. <input name="forceState" id="forceStateIframe" type="radio">
  3070. <label for="forceStateIframe">Iframe</label>
  3071. </div>
  3072. <div title="${i18n('forceStateDynamic')}">
  3073. <input name="forceState" id="forceStateDynamic" type="radio">
  3074. <label for="forceStateDynamic">Dynamic</label>
  3075. </div>
  3076. <div title="${i18n('forceStateDisable')}">
  3077. <input name="forceState" id="forceStateDisable" type="radio">
  3078. <label for="forceStateDisable">Disable</label>
  3079. </div>
  3080. </div>
  3081. <button id="nextSwitch" class="command" title="${i18n("nextSwitch")}" type="button">${i18n("nextSwitch")}</button>
  3082. <button id="loadNow" class="command" title="${i18n("loadNow")}" type="button">${i18n("loadNow")}</button>
  3083. <div>
  3084. <textarea style="display: none;" class="tempRule" spellcheck="false" placeholder="{rule object}"></textarea>
  3085. <button id="showDetail" title="" type="button">
  3086. <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>
  3087. </button>
  3088. <button id="saveDetail" title="" type="button">
  3089. <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>
  3090. </button>
  3091. </div>
  3092. `);
  3093. let forceStateIframe = frame.querySelector("#forceStateIframe");//forceState 1 禁用 2 强嵌 3 动态
  3094. let forceStateDynamic = frame.querySelector("#forceStateDynamic");
  3095. let forceStateDisable = frame.querySelector("#forceStateDisable");
  3096. let clickRadio = e => {
  3097. let radio = e.currentTarget.querySelector('input');
  3098. if (radio.checked) {
  3099. forceState = "";
  3100. } else {
  3101. switch (radio.id) {
  3102. case "forceStateIframe":
  3103. forceState = 2;
  3104. break;
  3105. case "forceStateDynamic":
  3106. forceState = 3;
  3107. break;
  3108. case "forceStateDisable":
  3109. forceState = 1;
  3110. break;
  3111. default:
  3112. return;
  3113. }
  3114. }
  3115. storage.setItem("forceState_"+location.host, forceState);
  3116. self.close();
  3117. location.reload();
  3118. };
  3119. forceStateIframe.parentNode.addEventListener("mousedown", clickRadio);
  3120. forceStateDynamic.parentNode.addEventListener("mousedown", clickRadio);
  3121. forceStateDisable.parentNode.addEventListener("mousedown", clickRadio);
  3122. if (forceState == 1) forceStateDisable.checked = true;
  3123. else if (forceState == 2) forceStateIframe.checked = true;
  3124. else if (forceState == 3) forceStateDynamic.checked = true;
  3125. let closeBtn = frame.querySelector(".closePicker");
  3126. let homeBtn = frame.querySelector(".logoToHome");
  3127. let title = frame.querySelector(".title");
  3128. let allpath = frame.querySelector(".allpath");
  3129. let selectorInput = frame.querySelector(".selector");
  3130. let xpath = frame.querySelector("#checkbox_id");
  3131. let checkBtn = frame.querySelector("#check");
  3132. let editBtn = frame.querySelector("#edit");
  3133. let nextSwitch = frame.querySelector("#nextSwitch");
  3134. let loadNow = frame.querySelector("#loadNow");
  3135. let tempRule = frame.querySelector(".tempRule");
  3136. let showDetailBtn = frame.querySelector("#showDetail");
  3137. let saveDetailBtn = frame.querySelector("#saveDetail");
  3138. showDetailBtn.addEventListener("click", e => {
  3139. if (tempRule.style.display == "none") {
  3140. tempRule.style.display = "";
  3141. showDetailBtn.classList.add("showDetail");
  3142. } else {
  3143. tempRule.style.display = "none";
  3144. showDetailBtn.classList.remove("showDetail");
  3145. }
  3146. }, true);
  3147. saveDetailBtn.addEventListener("click", e => {
  3148. let editTemp = self.getTempRule();
  3149. if(!ruleParser.customRules) {
  3150. ruleParser.customRules = [];
  3151. }
  3152. for (let i in ruleParser.customRules) {
  3153. if (ruleParser.customRules[i].url == editTemp.url) {
  3154. ruleParser.customRules.splice(i, 1);
  3155. break;
  3156. }
  3157. }
  3158. ruleParser.customRules.unshift(editTemp);
  3159. storage.setItem("customRules", ruleParser.customRules);
  3160. storage.setItem("hpRules", []);
  3161. if (window.confirm("Edit completed, reload page now?")) {
  3162. setTimeout(() => {location.reload()}, 100);
  3163. }
  3164. }, true);
  3165. nextSwitch.addEventListener("click", e => {
  3166. self.close();
  3167. NextSwitch.getInstance().start();
  3168. }, true);
  3169. loadNow.addEventListener("click", e => {
  3170. self.close();
  3171. let loadNum=window.prompt(i18n("loadConfirm"), "1");
  3172. if(loadNum==="" || loadNum===null)return;
  3173. autoLoadNum=Math.abs(parseInt(loadNum));
  3174. nextPage();
  3175. }, true);
  3176. closeBtn.addEventListener("click", e => {
  3177. self.close();
  3178. }, true);
  3179. homeBtn.addEventListener("click", e => {
  3180. _GM_openInTab(configPage[0], {active: true});
  3181. }, true);
  3182. let moving = false;
  3183. let moveHanlder = e => {
  3184. frame.style.left = e.clientX - 200 + "px";
  3185. frame.style.top = e.clientY - 15 + "px";
  3186. e.stopPropagation();
  3187. e.preventDefault();
  3188. };
  3189. let upHanlder = e => {
  3190. moving = false;
  3191. document.removeEventListener("mousemove", moveHanlder, true);
  3192. title.removeEventListener("mouseup", upHanlder, true);
  3193. e.stopPropagation();
  3194. e.preventDefault();
  3195. };
  3196. title.addEventListener("mousedown", e => {
  3197. moving = true;
  3198. document.addEventListener("mousemove", moveHanlder, true);
  3199. title.addEventListener("mouseup", upHanlder, true);
  3200. });
  3201. frame.addEventListener("mouseenter", e => {
  3202. if (moving) return;
  3203. if (self.mainSignDiv.parentNode) self.mainSignDiv.parentNode.removeChild(self.mainSignDiv);
  3204. self.checkInputSelector();
  3205. });
  3206. frame.addEventListener("mouseleave", e => {
  3207. if (moving) return;
  3208. document.body.appendChild(self.mainSignDiv);
  3209. self.clearSigns();
  3210. });
  3211. checkBtn.addEventListener("click", e => {
  3212. self.checkInputSelector();
  3213. if (this.selectorInput.value) _GM_setClipboard(this.selectorInput.value);
  3214. });
  3215. xpath.addEventListener("click", e => {
  3216. if (!selectorInput.value) {
  3217. self.setSelectorDiv("");
  3218. return;
  3219. }
  3220. let element = getElement(selectorInput.value, document);
  3221. let selector = self.getSelectorFromEle(element);
  3222. self.setSelectorDiv(selector);
  3223. selectorInput.value = selector;
  3224. });
  3225. editBtn.addEventListener("click", e => {
  3226. rulesData.editTemp = self.getTempRule();
  3227. storage.setItem("rulesData", rulesData);
  3228. _GM_openInTab(configPage[0], {active: true});
  3229. });
  3230. this.frame = frame;
  3231. this.xpath = xpath;
  3232. this.allpath = allpath;
  3233. this.selectorInput = selectorInput;
  3234. this.nextSwitch = nextSwitch;
  3235. this.loadNow = loadNow;
  3236. this.tempRule = tempRule;
  3237. this.moveHandler = e => {
  3238. if (e.target === document) return;
  3239. self.adjustSignDiv(self.mainSignDiv, self.getTarget(e.target));
  3240. };
  3241. this.clickHandler = e => {
  3242. if (self.inPicker) {
  3243. e.stopPropagation();
  3244. e.preventDefault();
  3245. }
  3246. let target = self.getTarget(e.target);
  3247. let selector = self.getSelectorFromEle(target);
  3248. selectorInput.value = selector;
  3249. self.setSelectorDiv(selector);
  3250. };
  3251. }
  3252.  
  3253. getTempRule() {
  3254. if (this.tempRule.value) {
  3255. try {
  3256. this.editTemp = JSON.parse(this.tempRule.value);
  3257. } catch (e) {
  3258. this.editTemp = null;
  3259. }
  3260. }
  3261. if (!this.editTemp) {
  3262. if (ruleParser.curSiteRule.url && !ruleParser.curSiteRule.singleUrl) {
  3263. this.editTemp = ruleParser.curSiteRule;
  3264. } else {
  3265. this.editTemp = {
  3266. name: document.title,
  3267. url: "^" + location.origin.replace(/^https?/, "https?").replace(/\./g,"\\.") + "/"
  3268. };
  3269. }
  3270. delete this.editTemp.from;
  3271. delete this.editTemp.type;
  3272. delete this.editTemp.updatedAt;
  3273. }
  3274. let selectorInput = this.frame.querySelector(".selector");
  3275. if (selectorInput.value) {
  3276. this.editTemp.pageElement = selectorInput.value;
  3277. }
  3278. return this.editTemp;
  3279. }
  3280.  
  3281. getTarget(ele) {
  3282. while (ele.parentNode && (ele.scrollWidth === 0 || ele.scrollHeight === 0)) {
  3283. ele = ele.parentNode;
  3284. }
  3285. return ele;
  3286. }
  3287.  
  3288. close() {
  3289. this.clearSigns();
  3290. if (this.frame.parentNode) this.frame.parentNode.removeChild(this.frame);
  3291. if (this.mainSignDiv.parentNode) this.mainSignDiv.parentNode.removeChild(this.mainSignDiv);
  3292. document.body.classList.remove("pagetual-picker");
  3293. document.body.removeEventListener("mousemove", this.moveHandler, true);
  3294. document.body.removeEventListener("click", this.clickHandler, true);
  3295. this.inPicker = false;
  3296. }
  3297.  
  3298. setImportant(ele, prop, value) {
  3299. ele.style.setProperty(prop, value, "important");
  3300. }
  3301.  
  3302. createSignDiv() {
  3303. let signDiv = document.createElement("div");
  3304. this.setImportant(signDiv, "position", "absolute");
  3305. this.setImportant(signDiv, "pointer-events", "none");
  3306. this.setImportant(signDiv, "z-index", "2147483647");
  3307. this.setImportant(signDiv, "background", "rgba(120, 170, 210, 0.6)");
  3308. this.setImportant(signDiv, "transition", "all 0.15s ease-out");
  3309. this.setImportant(signDiv, "box-shadow", "rgb(0 0 0) 0px 0px 3px 0px");
  3310. return signDiv;
  3311. }
  3312.  
  3313. adjustSignDiv(div, target) {
  3314. let rect = target.getBoundingClientRect();
  3315. this.setImportant(div, "width", rect.width + "px");
  3316. this.setImportant(div, "height", rect.height + "px");
  3317. this.setImportant(div, "left", rect.left + window.scrollX + "px");
  3318. this.setImportant(div, "top", rect.top + window.scrollY + "px");
  3319. }
  3320.  
  3321. getSelectorFromEle(ele) {
  3322. return this.xpath.checked ? createXPathFromElement(ele) : geneSelector(ele, true);
  3323. }
  3324.  
  3325. setSelectorDiv(selector) {
  3326. this.tempRule.value = JSON.stringify(this.getTempRule(), null, 4);
  3327. let self = this;
  3328. this.allpath.innerHTML = createHTML("");
  3329. if (!selector) return;
  3330. if (this.xpath.checked) {
  3331. let span = document.createElement("span");
  3332. span.innerText = selector;
  3333. span.addEventListener("click", e => {
  3334. self.selectorInput.value = selector;
  3335. self.checkInputSelector();
  3336. }, true);
  3337. this.allpath.appendChild(span);
  3338. } else {
  3339. selector.split(">").forEach((item, index) => self.geneSelectorItem(item, index));
  3340. }
  3341. }
  3342.  
  3343. geneSelectorItem(item, index) {
  3344. let self = this;
  3345. item = item.trim();
  3346. if (!item) return;
  3347. if (index !== 0) {
  3348. let span = document.createElement("span");
  3349. span.innerText = " > ";
  3350. this.allpath.appendChild(span);
  3351. }
  3352. let span = document.createElement("span");
  3353. span.className = "path";
  3354. span.innerText = item;
  3355. span.addEventListener("click", e => {
  3356. let selector = "";
  3357. let target = e.target;
  3358. while (target) {
  3359. selector = target.innerText + selector;
  3360. target = target.previousElementSibling;
  3361. }
  3362. self.selectorInput.value = selector;
  3363. self.checkInputSelector();
  3364. }, true);
  3365. this.allpath.appendChild(span);
  3366. }
  3367.  
  3368. checkInputSelector() {
  3369. let self = this;
  3370. this.clearSigns();
  3371. if (!this.selectorInput.value) return;
  3372. let eles = getAllElements(this.selectorInput.value, document);
  3373. if (eles && eles.length > 0) {
  3374. eles.forEach(ele => {
  3375. let sign = self.createSignDiv();
  3376. document.body.appendChild(sign);
  3377. self.adjustSignDiv(sign, ele);
  3378. self.signList.push(sign);
  3379. });
  3380. this.tempRule.value = JSON.stringify(this.getTempRule(), null, 4);
  3381. }
  3382. }
  3383.  
  3384. clearSigns() {
  3385. this.signList.forEach(sign => {
  3386. if (sign.parentNode) sign.parentNode.removeChild(sign);
  3387. });
  3388. this.signList = [];
  3389. }
  3390.  
  3391. start() {
  3392. if (this.inPicker) return;
  3393. this.inPicker = true;
  3394. if (!this.styleEle || !this.styleEle.parentNode) {
  3395. this.styleEle = _GM_addStyle(this.cssText);
  3396. }
  3397. document.documentElement.appendChild(this.frame);
  3398. document.body.appendChild(this.mainSignDiv);
  3399. document.body.classList.add("pagetual-picker");
  3400.  
  3401. document.body.addEventListener("mousemove", this.moveHandler, true);
  3402. document.body.addEventListener("click", this.clickHandler, true);
  3403. this.xpath.checked = isXPath(ruleParser.curSiteRule.pageElement);
  3404.  
  3405. this.loadNow.style.display = ruleParser.nextLinkHref ? "block" : "none";
  3406. if (ruleParser.curSiteRule.nextLink && Array && Array.isArray && Array.isArray(ruleParser.curSiteRule.nextLink)) {
  3407. this.nextSwitch.style.display = "block";
  3408. } else {
  3409. this.nextSwitch.style.display = "none";
  3410. }
  3411.  
  3412. let pageElementSel = ruleParser.curSiteRule.pageElement || "";
  3413. if (Array && Array.isArray && Array.isArray(pageElementSel)) {
  3414. pageElementSel = pageElementSel[nextIndex < pageElementSel.length ? nextIndex : 0];
  3415. }
  3416. this.setSelectorDiv(pageElementSel);
  3417. }
  3418. }
  3419.  
  3420. function createEdit(){
  3421. var options = {
  3422. mode: 'code',
  3423. modes: ['code', 'tree'],
  3424. templates: [
  3425. {
  3426. text: 'New site',
  3427. title: 'Insert a new site',
  3428. className: 'jsoneditor-type-object',
  3429. field: 'SiteTemplate',
  3430. value: {
  3431. 'name': 'Site name',
  3432. 'url': 'Site url'
  3433. }
  3434. }
  3435. ],
  3436. schema: {
  3437. "title": "Sites data",
  3438. "description": "Object containing site config",
  3439. "type": "array",
  3440. "items": {
  3441. "type": 'object',
  3442. "properties": {
  3443. "name": {
  3444. "title": "Site Name",
  3445. "description": "The site's name.",
  3446. "examples": [
  3447. "Google"
  3448. ],
  3449. "type": "string"
  3450. },
  3451. "url": {
  3452. "title": "Site Url",
  3453. "description": "The Regexp of site's url.",
  3454. "examples": [
  3455. "^https:\/\/yande\\.re\/"
  3456. ],
  3457. "type": "string"
  3458. }
  3459. },
  3460. "required": ["name", "url"]
  3461. }
  3462. }
  3463. };
  3464. var container = document.getElementById("jsoneditor");
  3465. container.style.height = '800px';
  3466. container.innerHTML = "";
  3467. var editor = new JSONEditor(container, options);
  3468. editor.set(ruleParser.customRules);
  3469. document.querySelector("#saveBtn").onclick=e=>{
  3470. try{
  3471. storage.setItem("hpRules", []);
  3472. storage.setItem("smartRules", []);
  3473. let customRules=editor.get();
  3474. if(!customRules){
  3475. storage.setItem("customRules", "");
  3476. }else{
  3477. if(Array && Array.isArray && !Array.isArray(customRules)){
  3478. showTips("Rules must be a Array!");
  3479. return;
  3480. }
  3481. debug(customRules);
  3482. storage.setItem("customRules", customRules);
  3483. }
  3484. }catch(e){
  3485. debug(e);
  3486. showTips("JSON error, check again!");
  3487. return;
  3488. }
  3489. showTips("Edit successfully");
  3490. };
  3491. }
  3492.  
  3493. function initConfig(){
  3494. initView();
  3495. listenUrl();
  3496. try{
  3497. if(_unsafeWindow.initedPagetual){
  3498. if(ruleImportUrlReg.test(location.href)){
  3499. showTips(i18n('duplicate'));
  3500. }
  3501. return true;
  3502. }
  3503. _unsafeWindow.initedPagetual=true;
  3504. }catch(e){}
  3505. _GM_registerMenuCommand(i18n(forceState==1?"enable":"disableSite"), ()=>{
  3506. forceState=(forceState==1?0:1);
  3507. storage.setItem("forceState_"+location.host, forceState);
  3508. showTips(i18n(forceState==1?"disableSiteTips":"enableSiteTips"));
  3509. if(!ruleParser.curSiteRule.url) location.reload();
  3510. });
  3511. _GM_registerMenuCommand(i18n("update"), ()=>{
  3512. updateRules(()=>{
  3513. showTips(i18n("updateSucc"));
  3514. location.reload();
  3515. },(rule,err)=>{
  3516. showTips("Update "+rule.url+" rules fail!");
  3517. });
  3518. showTips(i18n("beginUpdate"));
  3519. });
  3520. if(guidePage.test(location.href)){
  3521. if(typeof JSONEditor !== 'undefined'){
  3522. createEdit();
  3523. }else{
  3524. window.onload = e => {
  3525. createEdit();
  3526. }
  3527. }
  3528. return true;
  3529. }
  3530. if(location.href.indexOf("PagetualGuide")!=-1) return true;
  3531. if(location.hostname==="pagetual.hoothin.com") return true;
  3532.  
  3533. var configCon,insertPos;
  3534. var noRules=!rulesData.urls || rulesData.urls.length===0;
  3535.  
  3536. let inConfig = false;
  3537. for (let i = 0; i < configPage.length; i++) {
  3538. if (configPage[i] == location.href) {
  3539. inConfig = true;
  3540. break;
  3541. }
  3542. }
  3543. if(ruleImportUrlReg.test(location.href) || inConfig){
  3544. let importing = false;
  3545. if(noRules){
  3546. setTimeout(() => {
  3547. if (!importing) showTips(i18n("firstAlert"));
  3548. }, 3000);
  3549. setTimeout(() => {
  3550. if (!importing) showTips(i18n("firstAlert"));
  3551. }, 6000);
  3552. showTips(i18n("firstAlert"));
  3553. }
  3554. let defaultOption = document.querySelector('#discussion_rating_4');
  3555. if (defaultOption) defaultOption.checked = true;
  3556. let createImportBtn = () => {
  3557. let importBtn = document.createElement("button");
  3558. importBtn.innerText = i18n("import");
  3559. importBtn.style.marginTop = "100px";
  3560. importBtn.style.float = "right";
  3561. importBtn.style.position = "relative";
  3562. importBtn.style.display = "block";
  3563. importBtn.style.fontSize = "20px";
  3564. importBtn.addEventListener("click", e => {
  3565. let parentNode = importBtn.parentNode;
  3566. if (!parentNode) return;
  3567. parentNode.removeChild(importBtn);
  3568. try {
  3569. let rules=parentNode.innerText.trim();
  3570. let isContent=/['"]name['"]/i.test(rules);
  3571. if(isContent){
  3572. let ruleList=JSON.parse(`[${rules}]`);
  3573. for(let i in ruleList){
  3574. let hasRule = false;
  3575. let r = ruleList[i];
  3576. for(let j in ruleParser.customRules){
  3577. if(ruleParser.customRules[j].name == r.name){
  3578. ruleParser.customRules[j] = r;
  3579. hasRule = true;
  3580. break;
  3581. }
  3582. }
  3583. if(!hasRule)ruleParser.customRules.push(r);
  3584. }
  3585. storage.setItem("customRules", ruleParser.customRules);
  3586. storage.setItem("hpRules", []);
  3587. storage.setItem("smartRules", []);
  3588. showTips(i18n("importSucc"));
  3589. }else{
  3590. rules=rules.split("\n");
  3591. let diff=false;
  3592. for(let c=0;c<rules.length;c++){
  3593. let urlArr=rules[c].split("|"),url,type=1;
  3594. if(urlArr.length==1){
  3595. url=urlArr[0].trim();
  3596. if(!/^http/.test(url)){
  3597. showTips("Wrong url, check again!");
  3598. return;
  3599. }
  3600. }else if(urlArr.length==2){
  3601. type=urlArr[0].trim();
  3602. url=urlArr[1].trim();
  3603. if(!/^http/.test(url)){
  3604. showTips("Wrong url, check again!");
  3605. return;
  3606. }
  3607. }else{
  3608. break;
  3609. }
  3610. let maxId=0,hasUrl=false;
  3611. if(!rulesData.urls){
  3612. rulesData.urls=[];
  3613. maxId=1;
  3614. }else{
  3615. rulesData.urls.forEach(u=>{
  3616. if(maxId<u.id){
  3617. maxId=u.id;
  3618. }
  3619. if(u.url==url){
  3620. hasUrl=true;
  3621. }
  3622. });
  3623. if(hasUrl)break;
  3624. }
  3625. diff=true;
  3626. if(!rulesData.sort)rulesData.sort=[1];
  3627. rulesData.urls.push({id:maxId+1,url:url,type:type});
  3628. rulesData.sort.unshift(maxId+1);
  3629. }
  3630. if(!diff){
  3631. showTips("Already exists!");
  3632. return;
  3633. }
  3634. storage.setItem("rulesData", rulesData);
  3635.  
  3636. if(rulesData.urls)ruleUrls=ruleUrls.concat(rulesData.urls);
  3637. if(rulesData.sort){
  3638. let urls=[];
  3639. rulesData.sort.forEach(id=>{
  3640. for(let s=0;s<ruleUrls.length;s++){
  3641. if(id==ruleUrls[s].id){
  3642. urls.push(ruleUrls[s]);
  3643. break;
  3644. }
  3645. }
  3646. });
  3647. ruleUrls=urls;
  3648. }
  3649. updateRules(()=>{
  3650. showTips(i18n("updateSucc"));
  3651. location.reload();
  3652. },(rule,err)=>{
  3653. showTips("Update "+rule.url+" rules fail!");
  3654. });
  3655. importing = true;
  3656. showTips(i18n("beginUpdate"));
  3657. }
  3658. } catch (e) {
  3659. _GM_notification(e.toString());
  3660. }
  3661. });
  3662. return importBtn;
  3663. };
  3664. [].forEach.call(document.querySelectorAll('pre[name=pagetual],pre[name=user-content-pagetual]'), pre => {
  3665. let importBtn = createImportBtn();
  3666. let clientHeight = 35 - pre.clientHeight;
  3667. if (clientHeight > -20) clientHeight = -20;
  3668. importBtn.style.marginTop = `${clientHeight}px`;
  3669. pre.appendChild(importBtn);
  3670. });
  3671. document.addEventListener("mouseover", e => {
  3672. if (e.target.tagName === "PRE") {
  3673. let nameAttr=e.target.getAttribute("name");
  3674. if(nameAttr=="pagetual" || nameAttr=="user-content-pagetual"){
  3675. if (e.target.querySelector('button')) return;
  3676. let importBtn = createImportBtn();
  3677. let clientHeight = 35 - e.target.clientHeight;
  3678. if (clientHeight > -20) clientHeight = -20;
  3679. importBtn.style.marginTop = `${clientHeight}px`;
  3680. e.target.appendChild(importBtn);
  3681. }
  3682. }
  3683. });
  3684.  
  3685. if(inConfig){
  3686. _GM_addStyle(`
  3687. p>span:nth-child(1),p>span:nth-child(2),p>span:nth-child(3){
  3688. cursor: pointer;
  3689. user-select: none;
  3690. }
  3691. p>span:nth-child(1):hover,p>span:nth-child(2):hover,p>span:nth-child(3):hover{
  3692. color:red;
  3693. }
  3694. .updateDate{
  3695. cursor: pointer;
  3696. user-select: none;
  3697. }
  3698. .updateDate:hover{
  3699. color:red;
  3700. }
  3701. input[type=number]::-webkit-inner-spin-button,
  3702. input[type=number]::-webkit-outer-spin-button {
  3703. -webkit-appearance: none;
  3704. margin: 0;
  3705. }
  3706. input[type=number] {
  3707. -moz-appearance:textfield;
  3708. }
  3709. `);
  3710. document.querySelector("[name='user-content-click2import'],[name='click2import']").innerText=i18n("click2ImportRule")
  3711. configCon=document.querySelector(".markdown-body");
  3712. insertPos=configCon.querySelector("hr");
  3713.  
  3714. if(!noRules){
  3715. document.querySelector("pre[name='user-content-pagetual'],pre[name='pagetual']").style.display="none";
  3716. document.querySelector("p[name='user-content-click2import'],p[name='click2import']").style.display="none";
  3717. }
  3718. }else return true;
  3719. }else return false;
  3720. class Rulebar {
  3721. init(ruleUrl){
  3722. this.ruleUrl=ruleUrl;
  3723. this.item=document.createElement("p");
  3724. this.item.dataset.id=this.ruleUrl.id;
  3725. let url=document.createElement("span");
  3726. url.innerHTML=ruleUrl.url;
  3727. let up=document.createElement("span");
  3728. up.innerHTML="↑ ";
  3729. up.title=i18n("sortTitle");
  3730. let down=document.createElement("span");
  3731. down.innerHTML="↓ ";
  3732. down.title=i18n("sortTitle");
  3733. let del=document.createElement("span");
  3734. del.innerHTML="× ";
  3735. up.onclick=e=>{
  3736. this.moveUp();
  3737. };
  3738. down.onclick=e=>{
  3739. this.moveDown();
  3740. };
  3741. del.onclick=e=>{
  3742. this.del();
  3743. };
  3744. this.item.appendChild(up);
  3745. this.item.appendChild(down);
  3746. this.item.appendChild(del);
  3747. this.item.appendChild(url);
  3748. configCon.insertBefore(this.item, insertPos);
  3749. }
  3750. saveSort(){
  3751. let sort=[];
  3752. [].forEach.call(this.item.parentNode.querySelectorAll("p[data-id]"), i=>{
  3753. sort.push(i.dataset.id);
  3754. });
  3755. rulesData.sort=sort;
  3756. let urls=[];
  3757. sort.forEach(id=>{
  3758. for(let s=0;s<ruleUrls.length;s++){
  3759. if(id==ruleUrls[s].id){
  3760. urls.push(ruleUrls[s]);
  3761. break;
  3762. }
  3763. }
  3764. });
  3765. ruleUrls=urls;
  3766. storage.setItem("rulesData", rulesData);
  3767. }
  3768. moveUp(){
  3769. let preE=this.item.previousElementSibling;
  3770. if(preE.tagName=="P" && preE.children.length>1){
  3771. this.item.parentNode.insertBefore(this.item,preE);
  3772. this.saveSort();
  3773. }
  3774. }
  3775. moveDown(){
  3776. let nextE=this.item.nextElementSibling;
  3777. if(nextE.tagName=="P" && nextE.children.length>1){
  3778. this.item.parentNode.insertBefore(nextE,this.item);
  3779. this.saveSort();
  3780. }
  3781. }
  3782. del(){
  3783. if(this.ruleUrl.id<2){
  3784. showTips(i18n("cantDel"));
  3785. }else if(window.confirm(i18n("confirmDel"))){
  3786. for(let u=0;u<rulesData.urls.length;u++){
  3787. if(this.ruleUrl.id==rulesData.urls[u].id){
  3788. rulesData.urls.splice(u,1);
  3789. break;
  3790. }
  3791. }
  3792. for(let u=0;u<ruleUrls.length;u++){
  3793. if(this.ruleUrl.id==ruleUrls[u].id){
  3794. ruleUrls.splice(u,1);
  3795. break;
  3796. }
  3797. }
  3798. for(let u=0;u<rulesData.sort.length;u++){
  3799. if(this.ruleUrl.id==rulesData.sort[u]){
  3800. rulesData.sort.splice(u,1);
  3801. break;
  3802. }
  3803. }
  3804. storage.setItem("rulesData", rulesData);
  3805. ruleParser.rules=ruleParser.rules.filter(item=>{return item.from!=this.ruleUrl.id});
  3806. storage.setItem("rules", ruleParser.rules);
  3807. this.item.parentNode.removeChild(this.item);
  3808. //location.reload();
  3809. }
  3810. }
  3811. }
  3812. let updateP=document.createElement("p"),i=0;
  3813. let now=new Date().getTime(),inUpdate=false;
  3814.  
  3815.  
  3816. let pastDate=(new Date(updateDate)).toString(),passStr;
  3817. let passTime=(now-updateDate)/1000;
  3818. if(isNaN(passTime)){
  3819. passStr=i18n("firstUpdate");
  3820. }else if(passTime<60){
  3821. passStr=i18n("passSec", parseInt(passTime))+" 👆 "+i18n("click2update");
  3822. }else if(passTime<60*60){
  3823. passStr=i18n("passMin", parseInt(passTime/60))+" 👆 "+i18n("click2update");
  3824. }else if(passTime<60*60*24){
  3825. passStr=i18n("passHour", parseInt(passTime/3600))+" 👆 "+i18n("click2update");
  3826. }else{
  3827. passStr=i18n("passDay", parseInt(passTime/86400))+" 👆 "+i18n("click2update");
  3828. }
  3829.  
  3830.  
  3831. updateP.className="updateDate";
  3832. updateP.innerHTML=passStr;
  3833. updateP.title=i18n("update")+" - "+pastDate;
  3834. updateP.onclick=e=>{
  3835. ruleParser.rules=[];
  3836. updateRules(()=>{
  3837. showTips(i18n("updateSucc"));
  3838. updateP.innerHTML=i18n("passSec", 0);
  3839. updateP.title=i18n("update");
  3840. },(rule,err)=>{
  3841. showTips("Update "+rule.url+" rules fail!");
  3842. });
  3843. showTips(i18n("beginUpdate"));
  3844. };
  3845. configCon.insertBefore(updateP, insertPos);
  3846. if(ruleUrls){
  3847. ruleUrls.forEach(ruleUrl=>{
  3848. var rulebar=new Rulebar();
  3849. rulebar.init(ruleUrl);
  3850. });
  3851. }
  3852. let customUrlsTitle=document.createElement("h2");
  3853. customUrlsTitle.innerHTML=i18n("customUrls");
  3854. configCon.insertBefore(customUrlsTitle, insertPos);
  3855. let customUrlsInput=document.createElement("textarea");
  3856. customUrlsInput.style.width="100%";
  3857. customUrlsInput.placeholder="http://wedata.net/databases/AutoPagerize/items_all.json";
  3858. customUrlsInput.spellcheck=false;
  3859. configCon.insertBefore(customUrlsInput, insertPos);
  3860.  
  3861. let btns=document.createElement("div");
  3862. btns.style.display="flex";
  3863. configCon.insertBefore(btns, insertPos);
  3864. let upBtnImg=document.createElement("div");
  3865. upBtnImg.style.width="50%";
  3866. let upBtnImgTitle=document.createElement("h2");
  3867. upBtnImgTitle.style.whiteSpace="nowrap";
  3868. upBtnImgTitle.style.overflow="auto";
  3869. upBtnImgTitle.innerHTML=i18n("upBtnImg");
  3870. upBtnImg.appendChild(upBtnImgTitle);
  3871. let upBtnImgInput=document.createElement("input");
  3872. upBtnImgInput.style.width="100%";
  3873. upBtnImgInput.placeholder="data:image/png;base64,UpBtn";
  3874. upBtnImgInput.value=rulesData.upBtnImg||'';
  3875. upBtnImgInput.spellcheck=false;
  3876. upBtnImg.appendChild(upBtnImgInput);
  3877. btns.appendChild(upBtnImg);
  3878.  
  3879. let downBtnImg=document.createElement("div");
  3880. downBtnImg.style.width="50%";
  3881. let downBtnImgTitle=document.createElement("h2");
  3882. downBtnImgTitle.style.whiteSpace="nowrap";
  3883. downBtnImgTitle.style.overflow="auto";
  3884. downBtnImgTitle.innerHTML=i18n("downBtnImg");
  3885. downBtnImg.appendChild(downBtnImgTitle);
  3886. let downBtnImgInput=document.createElement("input");
  3887. downBtnImgInput.style.width="100%";
  3888. downBtnImgInput.placeholder="data:image/png;base64,DownBtn";
  3889. downBtnImgInput.value=rulesData.downBtnImg||'';
  3890. downBtnImgInput.spellcheck=false;
  3891. downBtnImg.appendChild(downBtnImgInput);
  3892. btns.appendChild(downBtnImg);
  3893.  
  3894. let otherBtns=document.createElement("div");
  3895. otherBtns.style.display="flex";
  3896. configCon.insertBefore(otherBtns, insertPos);
  3897. let loadingText=document.createElement("div");
  3898. loadingText.style.width="100%";
  3899. let loadingTextTitle=document.createElement("h2");
  3900. loadingTextTitle.style.whiteSpace="nowrap";
  3901. loadingTextTitle.style.overflow="auto";
  3902. loadingTextTitle.innerHTML=i18n("loadingTextTitle");
  3903. loadingText.appendChild(loadingTextTitle);
  3904. let loadingTextInput=document.createElement("input");
  3905. loadingTextInput.value=rulesData.loadingText||'';
  3906. loadingTextInput.placeholder=i18n("loadingText");
  3907. loadingTextInput.style.width="100%";
  3908. loadingTextInput.style.margin="0";
  3909. loadingTextInput.spellcheck=false;
  3910. loadingText.appendChild(loadingTextInput);
  3911. otherBtns.appendChild(loadingText);
  3912.  
  3913. let opacity=document.createElement("div");
  3914. let opacityTitle=document.createElement("h2");
  3915. opacityTitle.style.whiteSpace="nowrap";
  3916. opacityTitle.style.overflow="visible";
  3917. opacityTitle.innerHTML=i18n("opacity");
  3918. opacity.appendChild(opacityTitle);
  3919. let opacityInput=document.createElement("input");
  3920. opacityInput.value=rulesData.opacity*100;
  3921. opacityInput.type="number";
  3922. opacityInput.style.width="110px";
  3923. opacityInput.style.margin="0";
  3924. opacityInput.placeholder=i18n("opacityPlaceholder");
  3925. opacityInput.spellcheck=false;
  3926. opacity.appendChild(opacityInput);
  3927. otherBtns.appendChild(opacity);
  3928.  
  3929. let pageElementCss=document.createElement("div");
  3930. pageElementCss.style.marginBottom="30px";
  3931. let pageElementCssTitle=document.createElement("h2");
  3932. pageElementCssTitle.innerHTML=i18n("pageElementCss");
  3933. pageElementCss.appendChild(pageElementCssTitle);
  3934. let pageElementCssInput=document.createElement("input");
  3935. pageElementCssInput.value=rulesData.pageElementCss||'';
  3936. pageElementCssInput.style.width="100%";
  3937. pageElementCssInput.style.margin="0";
  3938. pageElementCssInput.placeholder="font-size: xx-large;";
  3939. pageElementCssInput.spellcheck=false;
  3940. pageElementCss.appendChild(pageElementCssInput);
  3941. configCon.insertBefore(pageElementCss, insertPos);
  3942.  
  3943. let customCss=document.createElement("div");
  3944. customCss.style.marginBottom="50px";
  3945. let customCssTitle=document.createElement("h2");
  3946. customCssTitle.innerHTML=i18n("customCss");
  3947. customCss.appendChild(customCssTitle);
  3948. let customCssInput=document.createElement("textarea");
  3949. customCssInput.value=rulesData.customCss||'';
  3950. customCssInput.style.width="100%";
  3951. customCssInput.style.margin="0";
  3952. customCssInput.placeholder=".pagetual{\n}";
  3953. customCssInput.spellcheck=false;
  3954. customCss.appendChild(customCssInput);
  3955. configCon.insertBefore(customCss, insertPos);
  3956.  
  3957. let configTable=document.createElement("table");
  3958. configTable.style.width="100%";
  3959. let configTbody=document.createElement("tbody");
  3960. configTbody.style.width="100%";
  3961. configTbody.style.display="inline-table";
  3962. configTable.appendChild(configTbody);
  3963. configCon.insertBefore(configTable, insertPos);
  3964. function createCheckbox(innerText, val, tag, parentCheck, otherType) {
  3965. if (typeof val == 'undefined') val = "";
  3966. let title=document.createElement(tag || "h3");
  3967. title.innerHTML = innerText;
  3968. title.style.overflowWrap = "normal";
  3969. let input = document.createElement("input");
  3970. if (otherType === 'key') {
  3971. input.type = 'text';
  3972. input.setAttribute('readOnly', 'readonly');
  3973. input.addEventListener("keydown", e => {
  3974. if (e.key === 'Escape' || e.key === 'Backspace') input.value = '';
  3975. else input.value = e.key;
  3976. e.stopPropagation();
  3977. e.preventDefault();
  3978. });
  3979. } else {
  3980. input.type = otherType || "checkbox";
  3981. }
  3982. input.style.width = "30px";
  3983. input.style.height = "20px";
  3984. input.style.float = "left";
  3985. input.style.margin = "5px";
  3986. input.value = val;
  3987. input.checked = val;
  3988. let td = document.createElement("td");
  3989. td.appendChild(input);
  3990. if (parentCheck) {
  3991. title.style.margin = "0";
  3992. td.appendChild(title);
  3993. let parent = parentCheck.parentNode.nextElementSibling;
  3994. let tr = parent.querySelector("tr");
  3995. if (!tr) {
  3996. tr = document.createElement("tr");
  3997. parent.appendChild(tr);
  3998. }
  3999. tr.appendChild(td);
  4000. if (!parentCheck.checked) {
  4001. td.style.display = "none";
  4002. }
  4003. parentCheck.addEventListener("click", e => {
  4004. td.style.display = parentCheck.checked ? "" : "none";
  4005. });
  4006. } else {
  4007. let tr = document.createElement("tr");
  4008. tr.appendChild(td);
  4009. td = document.createElement("td");
  4010. td.appendChild(title);
  4011. tr.appendChild(td);
  4012. configTable.children[0].appendChild(tr);
  4013. }
  4014. return input;
  4015. }
  4016.  
  4017. let enableWhiteListInput=createCheckbox(i18n("autoRun"), rulesData.enableWhiteList!=true);
  4018. let enableDebugInput=createCheckbox(i18n("enableDebug"), rulesData.enableDebug!=false);
  4019. let enableHistoryInput=createCheckbox(i18n("enableHistory"), rulesData.enableHistory===true);
  4020. let enableHistoryAfterInsertInput=createCheckbox(i18n("enableHistoryAfterInsert"), rulesData.enableHistoryAfterInsert===true);
  4021. let openInNewTabInput=createCheckbox(i18n("openInNewTab"), rulesData.openInNewTab!=false);
  4022. let hidePageBarInput=createCheckbox(i18n("hideBar"), rulesData.opacity==0);
  4023. let hideLoadingIconInput=createCheckbox(i18n("hideLoadingIcon"), rulesData.hideLoadingIcon!=false);
  4024. let initRunInput=createCheckbox(i18n("initRun"), rulesData.initRun!=false);
  4025. let autoLoadNumInput=createCheckbox(i18n("autoLoadNum"), rulesData.autoLoadNum, "h4", initRunInput, "number");
  4026. let preloadInput=createCheckbox(i18n("preload"), rulesData.preload!=false);
  4027. let rateInput=createCheckbox(i18n("turnRate"), rulesData.rate, "h4", preloadInput, "number");
  4028. let dbClick2StopInput=createCheckbox(i18n("dbClick2Stop"), rulesData.dbClick2Stop);
  4029. let manualModeInput=createCheckbox(i18n("manualMode"), rulesData.manualMode);
  4030. let clickModeInput=createCheckbox(i18n("clickMode"), rulesData.clickMode);
  4031. let pageBarMenuInput=createCheckbox(i18n("pageBarMenu"), rulesData.pageBarMenu);
  4032. let arrowToScrollInput=createCheckbox(i18n("arrowToScroll"), rulesData.arrowToScroll);
  4033. let sideControllerInput=createCheckbox(i18n("sideController"), rulesData.sideController);
  4034.  
  4035. let hideBarInput = createCheckbox(i18n("hideBar"), rulesData.hideBar && !rulesData.hideBarButNoStop, "h4", dbClick2StopInput, 'radio');
  4036. hideBarInput.name = 'hideBar';
  4037. let hideBarButNoStopInput = createCheckbox(i18n("hideBarButNoStop"), rulesData.hideBarButNoStop, "h4", dbClick2StopInput, 'radio');
  4038. hideBarButNoStopInput.name = 'hideBar';
  4039. hideBarInput.addEventListener('mouseup', e => {
  4040. if (hideBarInput.checked) {
  4041. setTimeout(() => {hideBarInput.checked = false}, 0);
  4042. }
  4043. });
  4044. hideBarButNoStopInput.addEventListener('mouseup', e => {
  4045. if (hideBarButNoStopInput.checked) {
  4046. setTimeout(() => {hideBarButNoStopInput.checked = false}, 0);
  4047. }
  4048. });
  4049. hidePageBarInput.addEventListener('click', e => {
  4050. opacityInput.value=hidePageBarInput.checked?0:30;
  4051. });
  4052.  
  4053. let dbClick2StopCtrlInput=createCheckbox(i18n("dbClick2StopCtrl"), rulesData.dbClick2StopCtrl, "h4", dbClick2StopInput);
  4054. let dbClick2StopAltInput=createCheckbox(i18n("dbClick2StopAlt"), rulesData.dbClick2StopAlt, "h4", dbClick2StopInput);
  4055. let dbClick2StopShiftInput=createCheckbox(i18n("dbClick2StopShift"), rulesData.dbClick2StopShift, "h4", dbClick2StopInput);
  4056. let dbClick2StopMetaInput=createCheckbox(i18n("dbClick2StopMeta"), rulesData.dbClick2StopMeta, "h4", dbClick2StopInput);
  4057. let dbClick2StopKeyInput=createCheckbox(i18n("dbClick2StopKey"), rulesData.dbClick2StopKey, "h4", dbClick2StopInput, "key");
  4058.  
  4059. let customRulesTitle=document.createElement("h2");
  4060. customRulesTitle.innerHTML=i18n("customRules", location.href.replace('tree', 'edit').replace(/\/$/, '') + '/pagetualRules.json');
  4061. configCon.insertBefore(customRulesTitle, insertPos);
  4062. let customRulesInput=document.createElement("textarea");
  4063. customRulesInput.spellcheck=false;
  4064. configCon.insertBefore(customRulesInput, insertPos);
  4065. if(rulesData.editTemp){
  4066. if(!ruleParser.customRules){
  4067. ruleParser.customRules=[];
  4068. }
  4069. for(let i in ruleParser.customRules){
  4070. if(ruleParser.customRules[i].url==rulesData.editTemp.url){
  4071. ruleParser.customRules.splice(i, 1);
  4072. break;
  4073. }
  4074. }
  4075. ruleParser.customRules.unshift(rulesData.editTemp);
  4076. rulesData.editTemp=null;
  4077. storage.setItem("rulesData", rulesData);
  4078. customRulesInput.previousElementSibling.scrollIntoView();
  4079. }
  4080. customRulesInput.style.width="100%";
  4081. customRulesInput.style.height="800px";
  4082. 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]`;
  4083. customRulesInput.value=getFormatJSON(ruleParser.customRules);
  4084. let blacklistInput=document.createElement("textarea");
  4085. blacklistInput.style.width="100%";
  4086. blacklistInput.style.height="500px";
  4087. blacklistInput.style.display="none";
  4088. blacklistInput.spellcheck=false;
  4089. blacklistInput.placeholder="http://*.xxx.com/*/y";
  4090. blacklistInput.value=rulesData.blacklist?rulesData.blacklist.join("\n"):"";
  4091. let blacklistBtn=document.createElement("button");
  4092. blacklistBtn.innerText=i18n("editBlacklist");
  4093. blacklistBtn.style.width="100%";
  4094. blacklistBtn.onclick=e=>{
  4095. blacklistInput.style.display=blacklistInput.style.display=="none"?"":"none";
  4096. };
  4097. configCon.insertBefore(blacklistBtn, insertPos);
  4098. configCon.insertBefore(blacklistInput, insertPos);
  4099. let saveBtn=document.createElement("button");
  4100. saveBtn.innerHTML=i18n("save");
  4101. saveBtn.style.width="100%";
  4102. saveBtn.style.position="fixed";
  4103. saveBtn.style.zIndex="999";
  4104. saveBtn.style.bottom=0;
  4105. saveBtn.style.left=0;
  4106. saveBtn.style.fontSize="x-large";
  4107. configCon.insertBefore(saveBtn, insertPos);
  4108. saveBtn.onclick=e=>{
  4109. try{
  4110. storage.setItem("hpRules", []);
  4111. storage.setItem("smartRules", []);
  4112. if(customRulesInput.value==""){
  4113. storage.setItem("customRules", "");
  4114. }else{
  4115. let customRules=JSON.parse(customRulesInput.value);
  4116. if(Array && Array.isArray && !Array.isArray(customRules)){
  4117. showTips("Rules must be a Array!");
  4118. return;
  4119. }
  4120. debug(customRules);
  4121. storage.setItem("customRules", customRules);
  4122. customRulesInput.value=JSON.stringify(customRules, null, 4);
  4123. }
  4124. }catch(e){
  4125. debug(e);
  4126. showTips("JSON error, check again!");
  4127. return;
  4128. }
  4129. rulesData.opacity = opacityInput.value / 100;
  4130. rulesData.blacklist = blacklistInput.value ? blacklistInput.value.split("\n") : "";
  4131. rulesData.hideBar = hideBarInput.checked;
  4132. rulesData.hideBarButNoStop = hideBarButNoStopInput.checked;
  4133. rulesData.dbClick2Stop = dbClick2StopInput.checked;
  4134. rulesData.enableWhiteList = !enableWhiteListInput.checked;
  4135. rulesData.enableDebug = enableDebugInput.checked;
  4136. rulesData.enableHistory = enableHistoryInput.checked;
  4137. rulesData.enableHistoryAfterInsert = enableHistoryAfterInsertInput.checked;
  4138. rulesData.openInNewTab = openInNewTabInput.checked;
  4139. rulesData.hideLoadingIcon = hideLoadingIconInput.checked;
  4140. rulesData.initRun = initRunInput.checked;
  4141. rulesData.autoLoadNum = autoLoadNumInput.value !== "0" ? autoLoadNumInput.value : '';
  4142. rulesData.rate = rateInput.value;
  4143. rulesData.preload = preloadInput.checked;
  4144. rulesData.manualMode = manualModeInput.checked;
  4145. rulesData.clickMode = clickModeInput.checked;
  4146. rulesData.pageBarMenu = pageBarMenuInput.checked;
  4147. rulesData.arrowToScroll = arrowToScrollInput.checked;
  4148. if (rulesData.sideController != sideControllerInput.checked) {
  4149. rulesData.sideControllerPos = false;
  4150. }
  4151. rulesData.sideController = sideControllerInput.checked;
  4152. rulesData.pageElementCss = pageElementCssInput.value;
  4153. rulesData.customCss = customCssInput.value;
  4154. rulesData.upBtnImg = upBtnImgInput.value;
  4155. rulesData.downBtnImg = downBtnImgInput.value;
  4156. rulesData.loadingText = loadingTextInput.value;
  4157. rulesData.dbClick2StopCtrl = dbClick2StopCtrlInput.checked;
  4158. rulesData.dbClick2StopAlt = dbClick2StopAltInput.checked;
  4159. rulesData.dbClick2StopShift = dbClick2StopShiftInput.checked;
  4160. rulesData.dbClick2StopMeta = dbClick2StopMetaInput.checked;
  4161. rulesData.dbClick2StopKey = dbClick2StopKeyInput.value;
  4162. storage.setItem("rulesData", rulesData);
  4163. let customUrls = customUrlsInput.value.trim();
  4164. if (customUrls) {
  4165. customUrls = customUrls.split(/\n/);
  4166. for (let c = 0; c < customUrls.length; c++) {
  4167. let url;
  4168. if(/^0\s*\|/.test(customUrls[c])){
  4169. url=customUrls[c].replace(/^0\s*\|\s*/, "").trim();
  4170. if(!/^http/.test(url)){
  4171. showTips("Wrong url, check again!");
  4172. return;
  4173. }
  4174. }else{
  4175. url=customUrls[c].trim();
  4176. if(!/^http/.test(url)){
  4177. showTips("Wrong url, check again!");
  4178. return;
  4179. }
  4180. }
  4181. let maxId=1,hasUrl=false;
  4182. if(!rulesData.urls){
  4183. rulesData.urls=[];
  4184. }
  4185. ruleUrls.forEach(u=>{
  4186. if(maxId<u.id){
  4187. maxId=u.id;
  4188. }
  4189. if(u.url==url){
  4190. hasUrl=true;
  4191. }
  4192. });
  4193. if(hasUrl)break;
  4194. if(!rulesData.sort)rulesData.sort=[1];
  4195. rulesData.urls.push({id:maxId+1,url:url});
  4196. rulesData.sort.push(maxId+1);
  4197. storage.setItem("rulesData", rulesData);
  4198. }
  4199. }
  4200. showTips("The settings are saved, refresh to view");
  4201. //location.reload();
  4202. };
  4203. return true;
  4204. }
  4205.  
  4206. var inUpdate=false;
  4207. function updateRules(success,fail){
  4208. if(inUpdate)return;
  4209. inUpdate=true;
  4210. let ruleIndex=ruleUrls.length-1;
  4211. storage.setItem("hpRules", []);
  4212. storage.setItem("smartRules", []);
  4213. function addNextRule(){
  4214. if(ruleIndex<0){
  4215. let now=new Date().getTime();
  4216. storage.setItem("ruleLastUpdate", now);
  4217. storage.setItem("rules", ruleParser.rules);
  4218. inUpdate=false;
  4219. success();
  4220. }else{
  4221. let rule=ruleUrls[ruleIndex--];
  4222. ruleParser.addRuleByUrl(rule.url, rule.id, (json,err)=>{
  4223. if(!json){
  4224. fail(rule,err);
  4225. }
  4226. addNextRule();
  4227. })
  4228. }
  4229. }
  4230. addNextRule();
  4231. }
  4232.  
  4233. function objIsArr(obj) {
  4234. return obj &&
  4235. typeof obj === 'object' &&
  4236. typeof obj.length === 'number' &&
  4237. !(obj.propertyIsEnumerable('length'));
  4238. }
  4239.  
  4240. function isVisible(el, win) {
  4241. if(!el || !el.offsetParent)return false;
  4242. var loopable = true,
  4243. visible = el.tagName && win.getComputedStyle(el).display != 'none' && win.getComputedStyle(el).visibility != 'hidden';
  4244. while(loopable && visible) {
  4245. el = el.parentNode;
  4246.  
  4247. if(el && el.tagName && el.tagName!="BODY") {
  4248. visible = win.getComputedStyle(el).display != 'none' && win.getComputedStyle(el).visibility != 'hidden';
  4249. }else {
  4250. loopable = false;
  4251. }
  4252. }
  4253. return visible;
  4254. }
  4255.  
  4256. function getElementTop(ele) {
  4257. if (!ele) return 0;
  4258. var actualTop = ele.offsetTop;
  4259. var current = ele.offsetParent;
  4260. while (current) {
  4261. actualTop += current.offsetTop;
  4262. current = current.offsetParent;
  4263. }
  4264. return actualTop;
  4265. }
  4266.  
  4267. function getElementBottom(ele) {
  4268. return getElementTop(ele) + ele.offsetHeight;
  4269. }
  4270.  
  4271. function getFormatJSON(obj){
  4272. if(!objIsArr(obj) || obj.length === 0)return "";
  4273. return JSON.stringify(obj, null, 4);
  4274. let ret="[\n";
  4275. let len=obj.length,i=0,isLast;
  4276. obj.forEach(item=>{
  4277. ret+=" {\n";
  4278. let iLen=Object.keys(item).length,j=0;
  4279. for(let key in item){
  4280. isLast=(++j)==iLen;
  4281. let value=item[key];
  4282. if(objIsArr(value)){
  4283. let vstr="[",v=0,vIsLast=false;
  4284. value.forEach(vi=>{
  4285. vIsLast=(++v)==value.length;
  4286. vstr+="\""+vi.replace(/\\/g,"\\\\")+"\""+(vIsLast?"":",");
  4287. });
  4288. vstr+="]";
  4289. ret+=" \""+key+"\":"+vstr+""+(isLast?"":",")+"\n";
  4290. }else{
  4291. if(typeof value=="string"){
  4292. value=value.replace(/\\/g,"\\\\").replace(/"/g,"\\\"");
  4293. value="\""+value+"\"";
  4294. }
  4295. ret+=" \""+key+"\":"+value+""+(isLast?"":",")+"\n";
  4296. }
  4297. }
  4298. isLast=(++i)==len;
  4299. ret+=" }"+(isLast?"":",")+"\n";
  4300. });
  4301. ret+="]";
  4302. return ret;
  4303. }
  4304.  
  4305. function globMatch(first, second) {
  4306. if (first.length == 0 && second.length == 0){
  4307. return true;
  4308. }
  4309.  
  4310. if (first.length > 1 && first[0] == '*' &&
  4311. second.length == 0){
  4312. return false;
  4313. }
  4314.  
  4315. if ((first.length > 1 && first[0] == '?') ||
  4316. (first.length != 0 && second.length != 0 &&
  4317. first[0] == second[0])){
  4318. return globMatch(first.substring(1),
  4319. second.substring(1));
  4320. }
  4321.  
  4322. if (first.length > 0 && first[0] == '*'){
  4323. return globMatch(first.substring(1), second) ||
  4324. globMatch(first, second.substring(1));
  4325. }
  4326.  
  4327. return false;
  4328. }
  4329.  
  4330. function initRules(callback) {
  4331. /*0 wedata格式,1 pagetual格式*/
  4332. ruleUrls=[
  4333. {
  4334. id:1,
  4335. url:'http://wedata.net/databases/AutoPagerize/items_all.json',
  4336. type:0,
  4337. }
  4338. ];var i=0,j=0;
  4339.  
  4340. ruleParser.initSavedRules(()=>{
  4341. storage.getItem("rulesData", data=>{
  4342. if(data){
  4343. rulesData=data;
  4344. if(data.urls)ruleUrls=ruleUrls.concat(data.urls);
  4345. if(data.sort){
  4346. let urls=[];
  4347. data.sort.forEach(id=>{
  4348. for(let s=0;s<ruleUrls.length;s++){
  4349. if(id==ruleUrls[s].id){
  4350. urls.push(ruleUrls[s]);
  4351. break;
  4352. }
  4353. }
  4354. });
  4355. ruleUrls=urls;
  4356. }
  4357. }
  4358. let upBtnImg=rulesData.upBtnImg,downBtnImg=rulesData.downBtnImg;
  4359. if(upBtnImg && downBtnImg){
  4360. downSvgCSS=downSvgCSS.replace("transform: rotate(180deg);","");
  4361. }else if(upBtnImg && !downBtnImg){
  4362. downBtnImg=upBtnImg;
  4363. }else if(downBtnImg && !upBtnImg){
  4364. upBtnImg=downBtnImg;
  4365. }
  4366. if(upBtnImg){
  4367. upSvg=`<img class="pagetual" src="${upBtnImg}"/>`;
  4368. }
  4369. if(downBtnImg){
  4370. downSvg=`<img class="pagetual" src="${downBtnImg}"/>`;
  4371. }
  4372. setLoadingDiv(rulesData.loadingText || i18n("loadingText"));
  4373. if(typeof(rulesData.opacity)=="undefined"){
  4374. rulesData.opacity=0.3;
  4375. }
  4376. if(typeof(rulesData.hideBar)=="undefined"){
  4377. rulesData.hideBar=false;
  4378. }
  4379. if(typeof(rulesData.dbClick2Stop)=="undefined"){
  4380. rulesData.dbClick2Stop=true;
  4381. }
  4382. if(typeof(rulesData.enableWhiteList)=="undefined"){
  4383. rulesData.enableWhiteList=false;
  4384. }
  4385. if(typeof(rulesData.enableHistory)=="undefined"){
  4386. rulesData.enableHistory=false;
  4387. }
  4388. if(typeof(rulesData.openInNewTab)=="undefined"){
  4389. rulesData.openInNewTab=true;
  4390. }
  4391. if(typeof(rulesData.enableDebug)=="undefined"){
  4392. rulesData.enableDebug=true;
  4393. }
  4394. if(typeof(rulesData.initRun)=="undefined"){
  4395. rulesData.initRun=true;
  4396. }
  4397. if(typeof(rulesData.preload)=="undefined"){
  4398. rulesData.preload=true;
  4399. }
  4400. if(typeof(rulesData.manualMode)=="undefined"){
  4401. rulesData.manualMode=false;
  4402. }
  4403. if(typeof(rulesData.clickMode)=="undefined"){
  4404. rulesData.clickMode=false;
  4405. }
  4406. if(typeof(rulesData.pageBarMenu)=="undefined"){
  4407. rulesData.pageBarMenu=false;
  4408. }
  4409. if(typeof(rulesData.arrowToScroll)=="undefined"){
  4410. rulesData.arrowToScroll=false;
  4411. }
  4412. if(typeof(rulesData.hideLoadingIcon)=="undefined"){
  4413. rulesData.hideLoadingIcon=false;
  4414. }
  4415. if(rulesData.blacklist && rulesData.blacklist.length>0){
  4416. for(let b in rulesData.blacklist){
  4417. let curGlob=rulesData.blacklist[b];
  4418. if(globMatch(curGlob, location.href)){
  4419. forceState==1;
  4420. return;
  4421. }
  4422. }
  4423. }
  4424. if(rulesData.autoLoadNum && rulesData.initRun){
  4425. autoLoadNum=parseInt(rulesData.autoLoadNum);
  4426. }
  4427. enableDebug=rulesData.enableDebug;
  4428. storage.getItem("nextSwitch_"+location.host, i=>{
  4429. storage.getItem("forceState_"+location.host, v=>{
  4430. storage.getItem("ruleLastUpdate", date=>{
  4431. if(typeof(i)!=="undefined"){
  4432. nextIndex=i;
  4433. }
  4434. if(typeof(v)=="undefined"){
  4435. v=(rulesData.enableWhiteList?1:0);
  4436. }
  4437. forceState=v;
  4438. updateDate=date;
  4439. if(initConfig())return;
  4440. if(forceState==1)return;
  4441. let now=new Date().getTime();
  4442. if(!date || now-date>2*24*60*60*1000){
  4443. updateRules(()=>{
  4444. },(rule,err)=>{});
  4445. storage.setItem("ruleLastUpdate", now);
  4446. }
  4447. callback();
  4448. });
  4449. });
  4450. });
  4451. });
  4452. });
  4453. }
  4454.  
  4455. function requestDoc(url, callback){
  4456. let postParams = url.match(/#p{(.*)}$/);
  4457. if (postParams) {
  4458. postParams = postParams[1];
  4459. url = url.replace(/#p{.*/, "");
  4460. }
  4461. _GM_xmlhttpRequest({
  4462. url: url,
  4463. method: postParams ? 'POST' : 'GET',
  4464. data: postParams,
  4465. overrideMimeType: 'text/html;charset=' + (document.characterSet || document.charset || document.inputEncoding),
  4466. headers: {
  4467. 'Referer': location.href,
  4468. 'User-Agent': navigator.userAgent,
  4469. "Content-Type": (postParams ? "application/x-www-form-urlencoded" : "text/html") + ";charset=" + (document.characterSet || document.charset || document.inputEncoding),
  4470. },
  4471. timeout: 20000,
  4472. onload: function(res) {
  4473. var doc = null, response = res.response;
  4474. let preCode = ruleParser.curSiteRule.pageElementPre || ruleParser.curSiteRule.pagePre;
  4475. if (preCode) {
  4476. try {
  4477. if (typeof _unsafeWindow.pagetualPagePre != 'undefined') {
  4478. response = _unsafeWindow.pagetualPagePre(response);
  4479. } else if (preCode.length == 2) {
  4480. response = response.replace(new RegExp(preCode[0], "gi"), preCode[1]);
  4481. } else {
  4482. response = Function("response",'"use strict";' + preCode)(response);
  4483. }
  4484. } catch(e) {
  4485. debug(e);
  4486. }
  4487. }
  4488. try {
  4489. doc = document.implementation.createHTMLDocument('');
  4490. doc.documentElement.innerHTML = response;
  4491. let base = doc.querySelector("base");
  4492. ruleParser.basePath = base ? base.href : url;
  4493. }
  4494. catch (e) {
  4495. debug('parse error:' + e.toString());
  4496. }
  4497. let pageElement = ruleParser.getPageElement(doc);
  4498. if (inCors && (!pageElement || pageElement.length == 0)) {
  4499. ruleParser.curSiteRule.pageElement = allOfBody;
  4500. pageElement = ruleParser.getPageElement(doc);
  4501. ruleParser.getInsert(true);
  4502. }
  4503. //只有1的話怕不是圖片哦
  4504. if (pageElement && (pageElement.length > 1 || (pageElement.length == 1 && pageElement[0].tagName != "IMG"))) {
  4505. ruleParser.insertPage(doc, pageElement, url, callback, false);
  4506. if (ruleParser.curSiteRule.action == 1) {
  4507. requestFromIframe(url, (doc, eles) => {
  4508. loadPageOver();
  4509. if (eles) {
  4510. ruleParser.insertPage(doc, eles, url, callback, true);
  4511. }
  4512. });
  4513. } else ruleParser.curSiteRule.action = 0;
  4514. } else if (ruleParser.curSiteRule.singleUrl || curPage == 1) {
  4515. ruleParser.curSiteRule.action = 1;
  4516. requestFromIframe(url, (doc, eles) => {
  4517. loadPageOver();
  4518. if (eles) {
  4519. ruleParser.insertPage(doc, eles, url, callback, true);
  4520. }
  4521. });
  4522. } else {
  4523. debug("Stop as no page element");
  4524. isPause = true;
  4525. callback(false);
  4526. }
  4527. },
  4528. onerror: function(e) {
  4529. debug(e, "NetError");
  4530. callback(false);
  4531. },
  4532. ontimeout: function(e) {
  4533. debug(e, "NetTimeout");
  4534. callback(false);
  4535. }
  4536. });
  4537. }
  4538.  
  4539. function initPage() {
  4540. ruleParser.initPage(() => {
  4541. if (ruleParser.curSiteRule.autoLoadNum) {
  4542. autoLoadNum = ruleParser.curSiteRule.autoLoadNum;
  4543. }
  4544. if (ruleParser.curSiteRule.nextLink && Array && Array.isArray && Array.isArray(ruleParser.curSiteRule.nextLink)) {
  4545. _GM_registerMenuCommand(i18n("nextSwitch"), () => {
  4546. NextSwitch.getInstance().start();
  4547. });
  4548. }
  4549. if (ruleParser.nextLinkHref) {
  4550. let isJs = /^(javascript|#)/.test(ruleParser.nextLinkHref.replace(location.href, ""));
  4551. if (!isJs) {
  4552. let inForce = (forceState == 2 || forceState == 3);
  4553. _GM_registerMenuCommand(i18n(inForce ? "cancelForceIframe" : "forceIframe"), () => {
  4554. if (inForce) {
  4555. storage.setItem("forceState_" + location.host, "");
  4556. } else {
  4557. let _state = ruleParser.curSiteRule.action > 0 || confirm(i18n("forceAllBody")) ? 2 : 3;
  4558. storage.setItem("forceState_" + location.host, _state);
  4559. }
  4560. location.reload();
  4561. });
  4562. }
  4563. _GM_registerMenuCommand(i18n("loadNow"), () => {
  4564. let loadNum = window.prompt(i18n("loadConfirm"), "1");
  4565. if (loadNum === "" || loadNum === null) return;
  4566. autoLoadNum = Math.abs(parseInt(loadNum));
  4567. nextPage();
  4568. });
  4569. }
  4570. initListener();
  4571. });
  4572. }
  4573.  
  4574. var pageBarStyle, mainStyleEle, mainStyleStyle;
  4575. function initView() {
  4576. if (!mainStyleStyle) {
  4577. mainStyleStyle = `
  4578. .pagetual_pageBar{
  4579. -moz-transition:opacity 0.3s ease-in-out 0s;
  4580. -webkit-transition:opacity 0.3s ease-in-out 0s;
  4581. transition:opacity 0.3s ease-in-out 0s;
  4582. font-family: Arial,sans-serif !important;
  4583. }
  4584. .pagetual_pageBar.stop {
  4585. -webkit-filter: invert(100%);
  4586. filter: invert(100%);
  4587. opacity: 1!important;
  4588. }
  4589. .pagetual_pageBar.hide {
  4590. display: none!important;
  4591. }
  4592. .pagetual_pageBar:hover {
  4593. opacity: 1!important;
  4594. }
  4595. .pagetual_pageBar span {
  4596. vertical-align: super;
  4597. }
  4598. .pagetual_pageBar a::before,
  4599. .pagetual_pageBar a::after {
  4600. content: none;
  4601. }
  4602. .pagetual_pageBar a>span {
  4603. margin-top: 0!important;
  4604. pointer-events: none;
  4605. padding: unset;
  4606. opacity: 0;
  4607. -moz-transition:all 0.3s ease-in-out 0s;
  4608. -webkit-transition:all 0.3s ease-in-out 0s;
  4609. transition:all 0.3s ease-in-out 0s;
  4610. }
  4611. .pagetual_pageBar a>span:hover {
  4612. color: red;
  4613. }
  4614. .pagetual_pageBar a:hover>span {
  4615. opacity: 1;
  4616. }
  4617. .pagetual_pageBar span.prevScreen,
  4618. .pagetual_pageBar span.nextScreen {
  4619. display: block!important;
  4620. }
  4621. .pagetual_pageBar a:hover>span.prevScreen {
  4622. margin-top: -30px!important;
  4623. pointer-events: all;
  4624. }
  4625. .pagetual_pageBar a:hover>span.nextScreen {
  4626. margin-top: 30px!important;
  4627. pointer-events: all;
  4628. }
  4629. .pagetual_pageBar span>svg {
  4630. -moz-transition:transform 0.5s ease, opacity 0.3s ease;
  4631. -webkit-transition:transform 0.5s ease, opacity 0.3s ease;
  4632. transition:transform 0.5 ease, opacity 0.3s ease;
  4633. opacity: 0;
  4634. }
  4635. .pagetual_pageBar:hover span>svg {
  4636. opacity: 1;
  4637. }
  4638. .pagetual_pageBar span>svg.upSvg:hover {
  4639. transform: rotate(360deg) scale3d(1.2, 1.2, 1.2);
  4640. }
  4641. .pagetual_pageBar span>svg.downSvg:hover {
  4642. transform: rotate(540deg) scale3d(1.2, 1.2, 1.2)!important;
  4643. }
  4644. .pagetual_pageBar .pagetual_pageNum{
  4645. color: #55555f;
  4646. }
  4647. .pagetual_pageBar .pagetual_pageNum:hover{
  4648. color: #ff6464;
  4649. }
  4650. .pagetual_tipsWords{
  4651. font-size: 50px;
  4652. font-weight: bold;
  4653. font-family: "黑体", -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto",
  4654. "Oxygen", "Ubuntu", "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji",
  4655. "Segoe UI Emoji", "Segoe UI Symbol";
  4656. color: #ffffff;
  4657. min-height: 70px;
  4658. max-width: 80%;
  4659. line-height: 70px;
  4660. position: fixed;
  4661. left: 50%;
  4662. top: 10%;
  4663. margin-left: -99999px;
  4664. padding: 0 15px;
  4665. z-index: 999999999;
  4666. background-color: #000;
  4667. border: 1px solid #303030;
  4668. border-radius: 10px;
  4669. opacity: 0;
  4670. filter: alpha(opacity=65);
  4671. box-shadow: 5px 5px 20px 0px #000;
  4672. -moz-transition:opacity 0.3s ease-in-out 0s;
  4673. -webkit-transition:opacity 0.3s ease-in-out 0s;
  4674. transition:opacity 0.3s ease-in-out 0s;
  4675. pointer-events: none;
  4676. }
  4677. .pagetual_loading {
  4678. width: 50px;
  4679. height: 50px;
  4680. margin: 10px auto;
  4681. border-radius: 100%;
  4682. display: flex;
  4683. -webkit-animation: pagetual_loading_scaleout 1.0s infinite ease-in-out;
  4684. animation: pagetual_loading_scaleout 1.0s infinite ease-in-out;
  4685. }
  4686. @-webkit-keyframes pagetual_loading_scaleout {
  4687. 0% { -webkit-transform: scale(0.0) }
  4688. 100% {
  4689. -webkit-transform: scale(1.0);
  4690. opacity: 0;
  4691. }
  4692. }
  4693. @keyframes pagetual_loading_scaleout {
  4694. 0% {
  4695. transform: scale(0.0);
  4696. -webkit-transform: scale(0.0);
  4697. } 100% {
  4698. transform: scale(1.0);
  4699. -webkit-transform: scale(1.0);
  4700. opacity: 0;
  4701. }
  4702. }
  4703. .pagetual_loading_text {
  4704. white-space: nowrap;
  4705. -webkit-animation: pagetual_loading_opacity 2.6s infinite ease-in-out;
  4706. animation: pagetual_loading_opacity 2.6s infinite ease-in-out;
  4707. }
  4708. @-webkit-keyframes pagetual_loading_opacity {
  4709. 0% { opacity: 1 }
  4710. 50% { opacity: 0.2 }
  4711. 100% { opacity: 1 }
  4712. }
  4713. @keyframes pagetual_loading_opacity {
  4714. 0% { opacity: 1 }
  4715. 50% { opacity: 0.2 }
  4716. 100% { opacity: 1 }
  4717. }
  4718. `;
  4719. pageBarStyle = `text-indent: initial;vertical-align: super;line-height:1;opacity:${rulesData.opacity};display:${rulesData.opacity==0?"none":"inline-flex"};padding:0;box-shadow: 0px 0px 10px 0px #000000aa;border-radius: 20px;background-color: rgb(240 240 240 / 80%);font-size: 30px;visibility: visible; position: initial; width: auto; height: 30px; float: none; clear: both; margin: 5px auto; text-align: center!important;justify-content: center;`;
  4720. }
  4721. if (!mainStyleEle || !mainStyleEle.parentNode) {
  4722. mainStyleEle = _GM_addStyle(mainStyleStyle);
  4723. }
  4724. }
  4725. var loadingDiv = document.createElement("div");
  4726. 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;";
  4727.  
  4728. 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;`;
  4729. function setLoadingDiv(loadingText) {
  4730. 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>`}`);
  4731. }
  4732.  
  4733. 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>`;
  4734. var upSvgCSS = `display:initial;position:relative;cursor: pointer;margin: 0 8px;width: 30px;height: 30px;vertical-align: middle;fill: currentColor;overflow: hidden;`;
  4735. 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>`;
  4736. 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);`;
  4737.  
  4738. 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;`;
  4739. 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;`;
  4740.  
  4741. var tipsWords = document.createElement("div");
  4742. tipsWords.className = "pagetual_tipsWords";
  4743.  
  4744. var isPause = false, isHideBar = false, isLoading = false, curPage = 1, forceState = 0, bottomGap = 1000, autoLoadNum = -1, nextIndex = 0, stopScroll = false, clickMode = false;
  4745.  
  4746. function changeStop(stop) {
  4747. isPause = stop;
  4748. [].forEach.call(document.querySelectorAll(".pagetual_pageBar,#pagetual-sideController"), bar => {
  4749. if (isPause) {
  4750. bar.classList.add("stop");
  4751. } else {
  4752. bar.classList.remove("stop");
  4753. }
  4754. });
  4755. }
  4756.  
  4757. function changeHideBar(hide) {
  4758. isHideBar = hide;
  4759. [].forEach.call(document.querySelectorAll(".pagetual_pageBar"), bar => {
  4760. if (isHideBar) {
  4761. bar.classList.add("hide");
  4762. } else {
  4763. bar.classList.remove("hide");
  4764. }
  4765. });
  4766. }
  4767.  
  4768. function isInViewPort(element) {
  4769. if(!document.body.contains(element))return false;
  4770. if(_unsafeWindow.getComputedStyle(element).display=="none")return false;
  4771. const viewWidth = window.innerWidth || document.documentElement.clientWidth;
  4772. const viewHeight = window.innerHeight || document.documentElement.clientHeight;
  4773. const {
  4774. top,
  4775. right,
  4776. bottom,
  4777. left,
  4778. } = element.getBoundingClientRect();
  4779.  
  4780. return (
  4781. top >= 0 &&
  4782. left >= 0 &&
  4783. right <= viewWidth + 1 &&
  4784. bottom <= viewHeight * 2
  4785. );
  4786. }
  4787.  
  4788. function getPageBar() {
  4789. let preBar = null, nextBar = null;
  4790. let pageBars = [].slice.call(document.querySelectorAll(".pagetual_pageBar"));
  4791. for (let i = 0; i < pageBars.length; i++) {
  4792. let pageBar = pageBars[i];
  4793. if (!pageBar || !document.body.contains(pageBar)) continue;
  4794. let {
  4795. top,
  4796. right,
  4797. bottom,
  4798. left,
  4799. } = pageBar.getBoundingClientRect();
  4800. if (top > 500) {
  4801. nextBar = pageBar;
  4802. preBar = (i - 1 >= 0 ? pageBars[i - 1] : null);
  4803. if (pageBar && document.body.contains(pageBar)) {
  4804. let {
  4805. top,
  4806. right,
  4807. bottom,
  4808. left,
  4809. } = pageBar.getBoundingClientRect();
  4810. if (top < -500) {
  4811. preBar = pageBar;
  4812. } else preBar = (i - 2 >= 0 ? pageBars[i - 2] : null);
  4813. }
  4814. break;
  4815. }
  4816. }
  4817. if (!nextBar) preBar = pageBars[pageBars.length - 2];
  4818. return {preBar: preBar, nextBar: nextBar};
  4819. }
  4820.  
  4821. var urlChanged=false;
  4822. var urlchangeHandler = e => {
  4823. if (ruleParser && ruleParser.curSiteRule && ruleParser.curSiteRule.listenUrlChange == false) return;
  4824. urlChanged = true;
  4825. isPause = true;
  4826. setTimeout(() => {
  4827. lastActiveUrl = location.href;
  4828. if (guidePage.test(location.href)) {
  4829. setTimeout(() => {
  4830. if(typeof JSONEditor !== 'undefined'){
  4831. createEdit();
  4832. }else{
  4833. window.onload = e => {
  4834. createEdit();
  4835. }
  4836. }
  4837. }, 500);
  4838. } else if (location.href == configPage[0]) {
  4839. location.reload();
  4840. } else {
  4841. if (!ruleParser.nextLinkHref) {
  4842. isLoading = false;
  4843. }
  4844. if (!isLoading && (ruleParser.curSiteRule.singleUrl || !ruleParser.ruleMatch(ruleParser.curSiteRule))) {
  4845. initPage();
  4846. }
  4847. }
  4848. },1);
  4849. };
  4850. window.addEventListener('pagetual_pushState', urlchangeHandler);
  4851. /*var _wr = function(type) {
  4852. var orig = history[type];
  4853. return function() {
  4854. var rv = orig.apply(this, arguments);
  4855. var e = new Event('pagetual_' + type);
  4856. e.arguments = arguments;
  4857. window.dispatchEvent(e);
  4858. return rv;
  4859. };
  4860. };
  4861. history.pushState = _wr('pushState');*/
  4862.  
  4863. function listenUrl() {
  4864. var prevState = window.location.pathname + window.location.search;
  4865. var checkUrlTime = 100;
  4866. var checkUrlTimer;
  4867. var checkFunc = () => {
  4868. if (forceState == 1) return;
  4869. if (checkUrlTime < 5000) {
  4870. checkUrlTime += checkUrlTime>>1;
  4871. }
  4872. let url = window.location.pathname + window.location.search;
  4873. if (prevState !== url && window.location.href != ruleParser.historyUrl) {
  4874. checkUrlTime = 2000;
  4875. prevState = url;
  4876. var e = new Event('pagetual_pushState');
  4877. e.arguments = arguments;
  4878. window.dispatchEvent(e);
  4879. }
  4880. clearTimeout(checkUrlTimer);
  4881. checkUrlTimer = setTimeout(checkFunc, checkUrlTime);
  4882. };
  4883. checkUrlTimer = setTimeout(checkFunc, checkUrlTime);
  4884.  
  4885. document.addEventListener("click", e => {
  4886. checkUrlTime = 1000;
  4887. clearTimeout(checkUrlTimer);
  4888. checkUrlTimer = setTimeout(checkFunc, checkUrlTime);
  4889. });
  4890. }
  4891.  
  4892. function distToBottom () {
  4893. let scrolly = window.scrollY;
  4894. let windowHeight = window.innerHeight || document.documentElement.clientHeight;
  4895. let scrollH = Math.max(document.documentElement.scrollHeight, document.body.scrollHeight);
  4896. return scrollH - scrolly - windowHeight;
  4897. }
  4898.  
  4899. let checkLoadMore, scrollHandler, clickToResetHandler, dblclickHandler, keydownHandler, hashchangeHandler, manualModeKeyHandler, pagetualNextHandler, keyupHandler;
  4900. function initListener () {
  4901. clearInterval(checkLoadMore);
  4902. document.removeEventListener('scroll', scrollHandler, true);
  4903. document.removeEventListener('wheel', scrollHandler, true);
  4904. document.removeEventListener('dblclick', dblclickHandler);
  4905. document.removeEventListener('keydown', keydownHandler);
  4906. window.removeEventListener('hashchange', hashchangeHandler, false);
  4907. document.removeEventListener('keydown', manualModeKeyHandler);
  4908. document.removeEventListener('pagetual.next', pagetualNextHandler, false);
  4909. document.removeEventListener('keyup', keyupHandler);
  4910. let loadmoreBtn, loading = true, lastScroll = 0, checkLoadMoreTimes = 0;
  4911. if (ruleParser.curSiteRule.loadMore) {
  4912. loading = false;
  4913. } else {
  4914. checkLoadMore = setInterval(() => {
  4915. loadmoreBtn = getLoadMore(document);
  4916. if (loadmoreBtn && isVisible(loadmoreBtn, _unsafeWindow)) {
  4917. loading = false;
  4918. clearInterval(checkLoadMore);
  4919. } else if (checkLoadMoreTimes++ > 30) {
  4920. clearInterval(checkLoadMore);
  4921. }
  4922. },300);
  4923. }
  4924. clickMode = typeof ruleParser.curSiteRule.clickMode == 'undefined' ? rulesData.clickMode : ruleParser.curSiteRule.clickMode;
  4925. let clickNext = async () => {
  4926. let nextLink = ruleParser.nextLinkHref;
  4927. if (!nextLink) return;
  4928. let isJs = /^(javascript|#)/.test(nextLink.replace(location.href, ""));
  4929. if (isJs) {
  4930. let nextBtn = await ruleParser.getNextLink(document);
  4931. if (nextBtn) emuClick(nextBtn);
  4932. } else {
  4933. window.location.href = nextLink;
  4934. }
  4935. };
  4936. let checkScrollReach = () => {
  4937. let dist = distToBottom();
  4938. if (clickMode) {
  4939. if (dist < 10) {
  4940. clickNext();
  4941. }
  4942. } else if (dist < bottomGap) {
  4943. nextPage();
  4944. }
  4945. };
  4946. scrollHandler = e => {
  4947. if (urlChanged && !isLoading) {
  4948. ruleParser.initPage(() => {
  4949. });
  4950. urlChanged = false;
  4951. }
  4952. if (isPause) return;
  4953. if (!loading) {
  4954. if (ruleParser.curSiteRule.loadMore || !loadmoreBtn || !document.body.contains(loadmoreBtn)) {
  4955. loadmoreBtn = getLoadMore(document);
  4956. }
  4957. if (loadmoreBtn) {
  4958. if (isInViewPort(loadmoreBtn)) {
  4959. emuClick(loadmoreBtn);
  4960. loading = true;
  4961. setTimeout(() => {loading = false}, 200);
  4962. }
  4963. } else {
  4964. loading = true;
  4965. setTimeout(() => {loading = false}, 200);
  4966. }
  4967. }
  4968. if (!isLoading && !stopScroll) {
  4969. checkScrollReach();
  4970. }
  4971. if (ruleParser.curSiteRule.lockScroll) {
  4972. let curScroll = document.body.scrollTop || document.documentElement.scrollTop;
  4973. if (isLoading && Math.abs(lastScroll - curScroll) > 350) {
  4974. document.body.scrollTop = lastScroll;
  4975. document.documentElement.scrollTop = lastScroll;
  4976. } else {
  4977. lastScroll = curScroll;
  4978. }
  4979. }
  4980. };
  4981. dblclickHandler = e => {
  4982. if (forceState == 1 || e.target.tagName == 'INPUT' || e.target.tagName == 'TEXTAREA') return;
  4983. if (!rulesData.dbClick2StopKey) {
  4984. if ((rulesData.dbClick2StopCtrl && !e.ctrlKey) ||
  4985. (rulesData.dbClick2StopAlt && !e.altKey) ||
  4986. (rulesData.dbClick2StopShift && !e.shiftKey) ||
  4987. (rulesData.dbClick2StopMeta && !e.metaKey)) {
  4988. return;
  4989. }
  4990. }
  4991. if (e.target.tagName !== "BODY" && e.target.className !== 'pagetual_pageBar') {
  4992. let selStr = document.getSelection().toString();
  4993. if (selStr && selStr.trim()) {
  4994. return;
  4995. }
  4996. }
  4997. if (rulesData.dbClick2Stop && (ruleParser.nextLinkHref || loadmoreBtn)) {
  4998. setTimeout(() => {
  4999. if (rulesData.hideBarButNoStop || rulesData.hideBar) {
  5000. changeHideBar(!isHideBar);
  5001. }
  5002. if (!rulesData.hideBarButNoStop) {
  5003. changeStop(!isPause);
  5004. showTips(i18n(isPause ? "disable" : "enable"));
  5005. }
  5006. if (!isPause) {
  5007. checkScrollReach();
  5008. }
  5009. }, 10);
  5010. }
  5011. };
  5012. document.addEventListener('dblclick', dblclickHandler);
  5013. clickToResetHandler = e => {
  5014. if (!ruleParser.nextLinkHref) isLoading = false;
  5015. };
  5016. document.addEventListener('click', clickToResetHandler);
  5017. if (rulesData.dbClick2StopKey) {
  5018. keydownHandler = e => {
  5019. if ((rulesData.dbClick2StopCtrl && !e.ctrlKey) ||
  5020. (rulesData.dbClick2StopAlt && !e.altKey) ||
  5021. (rulesData.dbClick2StopShift && !e.shiftKey) ||
  5022. (rulesData.dbClick2StopMeta && !e.metaKey)) {
  5023. return;
  5024. }
  5025. if (document.activeElement &&
  5026. (document.activeElement.tagName == 'INPUT' ||
  5027. document.activeElement.tagName == 'TEXTAREA')) {
  5028. return;
  5029. }
  5030. var key = e.key.toLowerCase();
  5031. if (rulesData.dbClick2StopKey.toLowerCase() == key) {
  5032. forceState = (forceState == 1 ? 0 : 1);
  5033. showTips(i18n(forceState == 1 ? "disableSiteTips" : "enableSiteTips"));
  5034. if (!ruleParser.curSiteRule.url) {
  5035. storage.setItem("forceState_" + location.host, forceState);
  5036. location.reload();
  5037. }
  5038. }
  5039. };
  5040. document.addEventListener('keydown', keydownHandler);
  5041. }
  5042. if (ruleParser.curSiteRule.listenHashChange) {
  5043. hashchangeHandler = () => {
  5044. urlChanged = true;
  5045. isPause = true;
  5046. if (!ruleParser.nextLinkHref) isLoading = false;
  5047. };
  5048. window.addEventListener('hashchange', hashchangeHandler, false);
  5049. }
  5050. let manualMode = typeof ruleParser.curSiteRule.manualMode == 'undefined' ? rulesData.manualMode : ruleParser.curSiteRule.manualMode;
  5051. if (manualMode) {
  5052. manualModeKeyHandler = e => {
  5053. if (document.activeElement &&
  5054. (document.activeElement.tagName == 'INPUT' ||
  5055. document.activeElement.tagName == 'TEXTAREA' ||
  5056. document.activeElement.contentEditable == 'true')) {
  5057. return;
  5058. }
  5059. if(e.keyCode == 39){
  5060. clickNext();
  5061. }
  5062. };
  5063. document.addEventListener('keydown', manualModeKeyHandler);
  5064. pagetualNextHandler = () => {
  5065. clickNext();
  5066. };
  5067. document.addEventListener('pagetual.next', pagetualNextHandler, false);
  5068. return;
  5069. }
  5070. if (rulesData.arrowToScroll) {
  5071. keyupHandler = e => {
  5072. if (document.activeElement &&
  5073. (document.activeElement.tagName == 'INPUT' ||
  5074. document.activeElement.tagName == 'TEXTAREA' ||
  5075. document.activeElement.contentEditable == 'true')) {
  5076. return;
  5077. }
  5078. if (e.keyCode == 39) {
  5079. let nextPageBar=getPageBar().nextBar;
  5080. if (nextPageBar) {
  5081. scrollToPageBar(nextPageBar);
  5082. } else {
  5083. let scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
  5084. window.scrollTo({ top: scrollTop + (window.innerHeight || document.documentElement.clientHeight), behavior: 'smooth'});
  5085. }
  5086. } else if (e.keyCode == 37) {
  5087. let prePageBar = getPageBar().preBar;
  5088. if (prePageBar) {
  5089. scrollToPageBar(prePageBar);
  5090. } else {
  5091. let scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
  5092. window.scrollTo({ top: scrollTop - (window.innerHeight || document.documentElement.clientHeight), behavior: 'smooth'});
  5093. }
  5094. }
  5095. };
  5096. document.addEventListener('keyup', keyupHandler);
  5097. }
  5098. if (!ruleParser.curSiteRule.wheel) {
  5099. document.addEventListener('scroll', scrollHandler, true);
  5100. }
  5101. document.addEventListener('wheel', scrollHandler, true);
  5102. }
  5103.  
  5104. function showTips(content, wordColor, backColor){
  5105. document.body.appendChild(tipsWords);
  5106. tipsWords.style.opacity=0.8;
  5107. tipsWords.innerText=content;
  5108. tipsWords.style.marginLeft=-tipsWords.offsetWidth/2+"px";
  5109. tipsWords.style.color=wordColor||0xFFFFFF;
  5110. tipsWords.style.backgroundColor=backColor||0x000;
  5111. setTimeout(()=>{tipsWords.style.opacity=0},1000);
  5112. }
  5113.  
  5114. function getLoadMore(doc) {
  5115. if (ruleParser.curSiteRule.loadMore === "") return null;
  5116. let btnSel = ruleParser.curSiteRule.loadMore || ".loadMore,.LoadMore,.load-more,.button-show-more,button[data-testid='more-results-button'],#btn_preview_remain", loadmoreBtn;
  5117. if (btnSel) {
  5118. loadmoreBtn = getElement(btnSel, doc);
  5119. }
  5120. if (!loadmoreBtn) {
  5121. let buttons = doc.querySelectorAll("input,button,a,div[onclick]"), loadmoreReg = /^\s*(加载更多|加載更多|(load|show)\s*more|もっと読み込む)\s*$/i;
  5122. for (let i = 0; i < buttons.length; i++) {
  5123. let button = buttons[i];
  5124. if (button.innerText.length > 20) continue;
  5125. if (button && loadmoreReg.test(button.innerText)) {
  5126. loadmoreBtn = button;
  5127. break;
  5128. }
  5129. }
  5130. }
  5131. if (loadmoreBtn && !ruleParser.curSiteRule.loadMore && loadmoreBtn.dataset.ajax !== "true") {
  5132. let href = loadmoreBtn.getAttribute("href");
  5133. if (href && href != "/" && !/^(javascript|#)/.test(href.replace(location.href,""))) {
  5134. loadmoreBtn = null;
  5135. }
  5136. }
  5137. return loadmoreBtn;
  5138. }
  5139.  
  5140. function scrollToPageBar(bar){
  5141. let yOffset = -20;
  5142. if (typeof ruleParser.curSiteRule.pageBarTop !== 'undefined') {
  5143. yOffset = -ruleParser.curSiteRule.pageBarTop;
  5144. }
  5145. const y = bar.getBoundingClientRect().top + window.pageYOffset + yOffset;
  5146. window.scrollTo({ top: y, behavior: 'smooth'});
  5147. }
  5148.  
  5149. const pageNumReg=/[&\/\?](p=|page[=\/_-]?)\d+|[_-]\d+\./;
  5150. function createPageBar(url) {
  5151. curPage++;
  5152. SideController.setup();
  5153. let posEle = null;
  5154. let scrollH = Math.max(document.documentElement.scrollHeight, document.body.scrollHeight);
  5155. let insert = ruleParser.getInsert();
  5156. if (!insert || !insert.parentNode) return;
  5157. posEle = insert;
  5158. while (posEle && !posEle.offsetParent) {
  5159. posEle = posEle.previousElementSibling || posEle.parentNode;
  5160. }
  5161. if (posEle) {
  5162. let actualBottom = getElementBottom(posEle);
  5163. bottomGap = scrollH - actualBottom + (window.innerHeight || document.documentElement.clientHeight) * (ruleParser.curSiteRule.rate || rulesData.rate || 1);
  5164. if (bottomGap < 100) bottomGap = 100;
  5165. } else {
  5166. bottomGap = 1000;
  5167. }
  5168. if (rulesData.opacity == 0 || ruleParser.curSiteRule.pageBar === 0) return null;
  5169. url = url.replace(/#p{.*/, "");
  5170. let example = ruleParser.curSiteRule.insertPos == 2 ? insert.children[0] : (insert.parentNode.children[parseInt(insert.parentNode.children.length / 2)] || insert);
  5171. if (example.className == "pagetual_pageBar") {
  5172. example = example.previousElementSibling;
  5173. }
  5174. if(!example || !example.parentNode)example=insert;
  5175. let exampleStyle = _unsafeWindow.getComputedStyle(example);
  5176. let inTable, inLi;
  5177. if (forceState == 2) {
  5178. inTable = inLi = false;
  5179. } else {
  5180. inTable=example.parentNode.tagName=="TABLE" ||
  5181. example.parentNode.tagName=="TBODY" ||
  5182. example.tagName=="TR" ||
  5183. example.tagName=="TBODY" ||
  5184. exampleStyle.display=="table-row" ||
  5185. (example.previousElementSibling && example.previousElementSibling.tagName=="TR") ||
  5186. (example.previousElementSibling && example.previousElementSibling.tagName=="TBODY");
  5187. inLi=example.tagName=="LI" || (example.previousElementSibling && example.previousElementSibling.tagName=="LI");
  5188. }
  5189. let pageBar=document.createElement(inTable?"tr":(inLi?"li":"div"));
  5190. let upSpan=document.createElement("span");
  5191. let downSpan=document.createElement("span");
  5192. let pageText=document.createElement("a");
  5193. let pageNum;
  5194. pageBar.className=isHideBar?"pagetual_pageBar hide":"pagetual_pageBar";
  5195. pageBar.id="pagetual_pageBar"+curPage;
  5196. pageBar.setAttribute("translate", "no");
  5197. if(isPause){
  5198. pageBar.classList.add("stop");
  5199. }
  5200. pageBar.style.cssText=pageBarStyle;
  5201. pageBar.title=i18n(isPause?"enable":"disable");
  5202. upSpan.innerHTML=upSvg;
  5203. upSpan.children[0].style.cssText=upSvgCSS;
  5204. upSpan.title=i18n("toTop");
  5205. downSpan.innerHTML=downSvg;
  5206. downSpan.children[0].style.cssText=downSvgCSS;
  5207. downSpan.title=i18n("toBottom");
  5208. upSpan.style.cssText=initStyle;
  5209. downSpan.style.cssText=initStyle;
  5210. pageText.href=url;
  5211. pageText.style.cssText=pageTextStyle;
  5212. pageText.title=i18n("current");
  5213. if(rulesData.openInNewTab)pageText.target="_blank";
  5214. pageBar.appendChild(upSpan);
  5215. pageBar.appendChild(pageText);
  5216. if(rulesData.pageBarMenu){
  5217. pageText.addEventListener("click", e=>{
  5218. e.stopPropagation();
  5219. if (e.ctrlKey || e.altKey || e.shiftKey || e.metaKey) return;
  5220. e.preventDefault();
  5221. Picker.getInstance().start();
  5222. });
  5223. }
  5224. let touched = false;
  5225. let touchBodyHandler = e => {
  5226. touched = false;
  5227. document.body.removeEventListener('touchstart', touchBodyHandler);
  5228. };
  5229. pageText.addEventListener("touchstart", e => {
  5230. if (touched) return;
  5231. touched = true;
  5232. pageText.style.pointerEvents = 'none';
  5233. setTimeout(() => {
  5234. pageText.style.pointerEvents = 'all';
  5235. }, 250);
  5236. document.body.addEventListener("touchstart", touchBodyHandler);
  5237. });
  5238. if(ruleParser.nextTitle){
  5239. pageText.innerHTML=ruleParser.nextTitle+" ";
  5240. pageText.title=ruleParser.nextTitle;
  5241. }
  5242. if(ruleParser.curSiteRule.pageNum || pageNumReg.test(url)){
  5243. pageText.innerHTML+="Page ";
  5244. pageNum=document.createElement("span");
  5245. pageNum.innerHTML=ruleParser.getPageNumFromUrl(url);
  5246. pageNum.className="pagetual_pageNum";
  5247. pageNum.title=i18n("inputPageNum");
  5248. pageNum.style.cssText=pageTextStyle;
  5249. pageNum.style.cursor="pointer";
  5250. pageNum.style.color="";
  5251. pageNum.style.marginLeft="5px";
  5252. pageNum.addEventListener("click", e=>{
  5253. let pageInput=prompt(i18n("inputPageNum"), "1");
  5254. if(pageInput){
  5255. let pageLink=ruleParser.getLinkByPage(url, pageInput);
  5256. if(pageLink){
  5257. _GM_openInTab(pageLink,{active:true});
  5258. }
  5259. }
  5260. e.preventDefault();
  5261. e.stopPropagation();
  5262. });
  5263. pageBar.appendChild(pageNum);
  5264. }else{
  5265. pageText.innerHTML+="Page "+curPage;
  5266. }
  5267. let preBtn=document.createElement("span");
  5268. preBtn.innerHTML="∧";
  5269. preBtn.title="Prev page";
  5270. preBtn.className="prevScreen";
  5271. 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";
  5272. let nextBtn=document.createElement("span");
  5273. nextBtn.innerHTML="∨";
  5274. nextBtn.title="Next page";
  5275. nextBtn.className="nextScreen";
  5276. 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";
  5277. let localPage=curPage;
  5278. preBtn.addEventListener("click", e=>{
  5279. e.stopPropagation();
  5280. e.preventDefault();
  5281. let prePageBar = document.querySelector("#pagetual_pageBar"+(localPage-1));
  5282. if (prePageBar) {
  5283. scrollToPageBar(prePageBar);
  5284. } else {
  5285. let scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
  5286. window.scrollTo({ top: scrollTop - (window.innerHeight || document.documentElement.clientHeight), behavior: 'smooth'});
  5287. }
  5288. });
  5289. nextBtn.addEventListener("click", e=>{
  5290. e.stopPropagation();
  5291. e.preventDefault();
  5292. let nextPageBar=document.querySelector("#pagetual_pageBar"+(localPage+1));
  5293. if (nextPageBar) {
  5294. scrollToPageBar(nextPageBar);
  5295. } else {
  5296. let nextEle = pageBar.parentNode.children[pageBar.parentNode.children.length - 1];
  5297. if (nextEle) scrollToPageBar(nextEle);
  5298. else {
  5299. scrollH=Math.max(document.documentElement.scrollHeight, document.body.scrollHeight);
  5300. window.scrollTo({ top: scrollH || 9999999, behavior: 'smooth'});
  5301. }
  5302. }
  5303. });
  5304. pageText.insertBefore(preBtn, pageText.firstChild);
  5305. pageText.insertBefore(nextBtn, pageText.firstChild);
  5306. pageBar.appendChild(downSpan);
  5307. if (forceState == 2) {
  5308. pageBar.style.width = "99%";
  5309. } else {
  5310. let parentStyle=_unsafeWindow.getComputedStyle(example.parentNode);
  5311. let parentWidth=example.parentNode.offsetWidth||parseInt(parentStyle.width);
  5312. pageBar.style.width=parentWidth-parseInt(parentStyle.paddingLeft)-parseInt(parentStyle.paddingRight)-10+"px";
  5313. pageBar.style.margin='10px 5px';
  5314. if(parentStyle.display=="grid" || parentStyle.display=="inline-grid"){
  5315. pageBar.style.gridColumnStart=1;
  5316. pageBar.style.gridColumnEnd=1+parseInt(example.parentNode.offsetWidth/example.offsetWidth);
  5317. }
  5318. if(inTable){
  5319. example=(example.tagName=="TR" || example.tagName=="TBODY")?example:example.previousElementSibling;
  5320. if(example.tagName=="TBODY")example=example.querySelector("tr");
  5321. let preTr=example;
  5322. while(preTr && preTr.children.length==0)preTr=preTr.previousElementSibling;
  5323. if(preTr)example=preTr;
  5324. let tdNum=0;
  5325. if (exampleStyle.display=="table-row") {
  5326. [].forEach.call(example.children, el=>{
  5327. tdNum+=el.colSpan||1;
  5328. });
  5329. } else {
  5330. [].forEach.call(example.children, el=>{
  5331. if(el.tagName=="TD" || el.tagName=="TH"){
  5332. tdNum+=el.colSpan||1;
  5333. }
  5334. });
  5335. }
  5336. pageBar.style.display="table-row";
  5337. pageBar.style.backgroundColor="unset";
  5338. pageBar.style.lineHeight="20px";
  5339. pageBar.style.boxShadow="";
  5340. pageBar.style.height="35px";
  5341. let td=document.createElement("td");
  5342. td.colSpan=tdNum||1;
  5343. let inTd=document.createElement("div");
  5344. inTd.style.backgroundColor="rgb(240 240 240 / 80%)";
  5345. inTd.style.borderRadius="20px";
  5346. inTd.style.padding="0 0";
  5347. inTd.style.margin="0";
  5348. inTd.style.lineHeight="20px";
  5349. inTd.style.textAlign="center";
  5350. inTd.style.boxShadow="rgb(0 0 0 / 67%) 0px 0px 10px 0px";
  5351. inTd.appendChild(upSpan);
  5352. inTd.appendChild(pageText);
  5353. if(pageNum)inTd.appendChild(pageNum);
  5354. inTd.appendChild(downSpan);
  5355. td.appendChild(inTd);
  5356. pageBar.appendChild(td);
  5357. }else if(inLi){
  5358. example=example.tagName=="LI"?example:example.previousElementSibling;
  5359. pageBar.style.display=getComputedStyle(example).display;
  5360. pageBar.style.backgroundColor="unset";
  5361. pageBar.style.lineHeight="20px";
  5362. pageBar.style.boxShadow="";
  5363. pageBar.style.height="35px";
  5364. let td=document.createElement("td");
  5365. td.colSpan=example.children.length;
  5366. td.style.width='100%';
  5367. let inTd=document.createElement("div");
  5368. inTd.style.backgroundColor="rgb(240 240 240 / 80%)";
  5369. inTd.style.borderRadius="20px";
  5370. inTd.style.margin="0"
  5371. inTd.style.padding="0 0";
  5372. inTd.style.textAlign="center";
  5373. inTd.style.minWidth="150px";
  5374. inTd.appendChild(upSpan);
  5375. inTd.appendChild(pageText);
  5376. inTd.style.width='calc(100% - 20px)';
  5377. inTd.style.boxShadow="rgb(0 0 0 / 67%) 0px 0px 10px 0px";
  5378. if(pageNum)inTd.appendChild(pageNum);
  5379. inTd.appendChild(downSpan);
  5380. if (pageBar.style.display === 'table-row') {
  5381. td.appendChild(inTd);
  5382. pageBar.appendChild(td);
  5383. } else {
  5384. inTd.style.width='100%';
  5385. pageBar.appendChild(inTd);
  5386. }
  5387. }
  5388. }
  5389.  
  5390. upSpan.addEventListener("click", e=>{
  5391. document.body.scrollTop=0;
  5392. document.documentElement.scrollTop=0;
  5393. e.preventDefault();
  5394. e.stopPropagation();
  5395. });
  5396. downSpan.addEventListener("click", e=>{
  5397. changeStop(true);
  5398. pageBar.title = i18n(isPause ? "enable" : "disable");
  5399. scrollH=Math.max(document.documentElement.scrollHeight, document.body.scrollHeight);
  5400. document.body.scrollTop = scrollH || 9999999;
  5401. document.documentElement.scrollTop = scrollH || 9999999;
  5402. e.preventDefault();
  5403. e.stopPropagation();
  5404. });
  5405. pageBar.addEventListener("click", e=>{
  5406. changeStop(!isPause);
  5407. pageBar.title=i18n(isPause?"enable":"disable");
  5408. });
  5409. ruleParser.insertElement(pageBar);
  5410. if(ruleParser.curSiteRule.pageBar && ruleParser.curSiteRule.pageBar !== 0){
  5411. try{
  5412. ((typeof _unsafeWindow.pagetualPageBar=='undefined') ? Function("pageBar",'"use strict";' + ruleParser.curSiteRule.pageBar) : _unsafeWindow.pagetualPageBar)(pageBar);
  5413. }catch(e){
  5414. debug(e);
  5415. }
  5416. }
  5417.  
  5418. return pageBar;
  5419. }
  5420.  
  5421. function emuClick(btn) {
  5422. let orgHref = btn.getAttribute('href');
  5423. if (orgHref && orgHref != "#") {
  5424. btn.setAttribute('href', orgHref.replace(/#$/,""));
  5425. }
  5426. if (!PointerEvent) return btn.click();
  5427. let eventParam = {
  5428. isTrusted: true,
  5429. altKey: false,
  5430. azimuthAngle: 0,
  5431. bubbles: true,
  5432. button: 0,
  5433. buttons: 0,
  5434. clientX: 1,
  5435. clientY: 1,
  5436. cancelBubble: false,
  5437. cancelable: true,
  5438. composed: true,
  5439. ctrlKey: false,
  5440. defaultPrevented: false,
  5441. detail: 1,
  5442. eventPhase: 2,
  5443. fromElement: null,
  5444. height: 1,
  5445. isPrimary: false,
  5446. metaKey: false,
  5447. pointerId: 1,
  5448. pointerType: "mouse",
  5449. pressure: 0,
  5450. relatedTarget: null,
  5451. returnValue: true,
  5452. shiftKey: false,
  5453. toElement: null,
  5454. twist: 0,
  5455. which: 1
  5456. };
  5457. let mouseEvent = new PointerEvent("mousedown",eventParam);
  5458. btn.dispatchEvent(mouseEvent);
  5459. mouseEvent = new PointerEvent("mouseup",eventParam);
  5460. btn.dispatchEvent(mouseEvent);
  5461. let dispatchTouchEvent = (ele, type) => {
  5462. let touchEvent;
  5463. try {
  5464. touchEvent = document.createEvent('TouchEvent')
  5465. touchEvent.initTouchEvent(type, true, true)
  5466. } catch (err) {
  5467. try {
  5468. touchEvent = document.createEvent('UIEvent')
  5469. touchEvent.initUIEvent(type, true, true)
  5470. } catch (err) {
  5471. touchEvent = document.createEvent('Event')
  5472. touchEvent.initEvent(type, true, true)
  5473. }
  5474. }
  5475. touchEvent.targetTouches = [{
  5476. pageX: 1,
  5477. pageY: 1,
  5478. clientX: 1,
  5479. clientY: 1,
  5480. target: btn
  5481. }];
  5482. touchEvent.touches = [{
  5483. pageX: 1,
  5484. pageY: 1,
  5485. clientX: 1,
  5486. clientY: 1,
  5487. target: btn
  5488. }];
  5489. touchEvent.changedTouches = [{
  5490. pageX: 1,
  5491. pageY: 1,
  5492. clientX: 1,
  5493. clientY: 1,
  5494. target: btn
  5495. }];
  5496. ele.dispatchEvent(touchEvent);
  5497. }
  5498. dispatchTouchEvent(btn, "touchstart");
  5499. dispatchTouchEvent(btn, "touchend");
  5500.  
  5501. btn.click();
  5502. if (orgHref && orgHref != "#") {
  5503. setTimeout(() => btn.setAttribute('href', orgHref), 0);
  5504. }
  5505. }
  5506.  
  5507. var failFromIframe = 0;
  5508. var inCors = false;
  5509. var checkRemoveIntv;
  5510. function requestFromIframe(url, callback){
  5511. url = url.indexOf('=') == -1 ? url.replace(/#[^#]*/,"") : url;
  5512. let iframe = document.createElement('iframe');
  5513. iframe.name = 'pagetual-iframe';
  5514. iframe.width = '100%';
  5515. iframe.height = '1000';
  5516. iframe.frameBorder = '0';
  5517. if (ruleParser.curSiteRule.sandbox != false) {
  5518. iframe.sandbox = "allow-same-origin allow-scripts allow-popups allow-forms";
  5519. }
  5520. 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;';
  5521. let waitTime = 100, checkEval;
  5522. if (ruleParser.curSiteRule.waitElement) {
  5523. checkEval = doc => {
  5524. return ruleParser.waitElement(doc);
  5525. };
  5526. } else if (ruleParser.curSiteRule.wait) {
  5527. if (isNaN(ruleParser.curSiteRule.wait)) {
  5528. try {
  5529. checkEval = (typeof _unsafeWindow.pagetualWait == 'undefined') ? Function("doc",'"use strict";' + ruleParser.curSiteRule.wait) : _unsafeWindow.pagetualWait;
  5530. } catch(e) {
  5531. debug(e);
  5532. }
  5533. } else {
  5534. waitTime = ruleParser.curSiteRule.wait;
  5535. }
  5536. }
  5537. if (checkRemoveIntv) clearInterval(checkRemoveIntv);
  5538. checkRemoveIntv = setInterval(() => {
  5539. if (!iframe || !document.body.contains(iframe)) {
  5540. clearInterval(checkRemoveIntv);
  5541. loadPageOver();
  5542. }
  5543. }, 500);
  5544. let loadedHandler = e => {
  5545. if(e.data != 'pagetual-iframe:DOMLoaded' && e.type != 'load') return;
  5546. clearInterval(checkRemoveIntv);
  5547. window.removeEventListener('message', loadedHandler, false);
  5548. iframe.removeEventListener('load', loadedHandler, false);
  5549. let tryTimes = 0;
  5550. function checkIframe() {
  5551. if (urlChanged || isPause) {
  5552. return callback(false, false);
  5553. }
  5554. try {
  5555. let doc = iframe.contentDocument || iframe.contentWindow.document;
  5556. let base = doc.querySelector("base");
  5557. ruleParser.basePath = base ? base.href : url;
  5558. let eles = ruleParser.getPageElement(doc, iframe.contentWindow);
  5559. if (checkEval && !checkEval(doc)) {
  5560. setTimeout(() => {
  5561. checkIframe();
  5562. }, waitTime);
  5563. return;
  5564. } else if (eles && eles.length > 0) {
  5565. callback(doc, eles);
  5566. } else if (tryTimes++ < 100) {
  5567. setTimeout(() => {
  5568. checkIframe();
  5569. }, waitTime);
  5570. return;
  5571. } else {
  5572. if (failFromIframe++ > 2) {
  5573. failFromIframe = 0;
  5574. debug("Stop as failFromIframe");
  5575. isPause = true;
  5576. callback(false, false);
  5577. } else {
  5578. callback(false, false);
  5579. }
  5580. }
  5581. } catch(e) {
  5582. inCors = true;
  5583. if (forceState === 3) {
  5584. debug("Stop as cors");
  5585. isPause = true;
  5586. }
  5587. if (!ruleParser.curSiteRule.pageElement) {
  5588. ruleParser.curSiteRule.pageElement = allOfBody;
  5589. ruleParser.getInsert(true);
  5590. }
  5591. ruleParser.curSiteRule.action = 0;
  5592. ruleParser.nextLinkHref = url;
  5593. callback(false, false);
  5594. nextPage();
  5595. }
  5596. if (iframe && iframe.parentNode) iframe.parentNode.removeChild(iframe);
  5597. }
  5598. setTimeout(() => {
  5599. checkIframe();
  5600. },waitTime);
  5601. };
  5602. window.addEventListener('message', loadedHandler, false);
  5603. iframe.addEventListener('load', loadedHandler, false);
  5604. iframe.src = url;
  5605. document.body.appendChild(iframe);
  5606. }
  5607.  
  5608. var emuIframe,lastActiveUrl;
  5609. function emuPage(callback) {
  5610. let orgPage=null,orgContent=null,preContent=null,iframeDoc,times=0,loadmoreBtn,pageEle,nextLink,loadmoreEnd=false,waitTimes=10,changed=false;
  5611. function returnFalse(log){
  5612. debug(log);
  5613. isPause=true;
  5614. callback(false, false);
  5615. if(emuIframe && emuIframe.parentNode){
  5616. emuIframe.parentNode.removeChild(emuIframe);
  5617. emuIframe=null;
  5618. }
  5619. }
  5620. async function checkPage(){
  5621. if(isPause)return loadPageOver();
  5622. try{
  5623. iframeDoc=emuIframe.contentDocument || emuIframe.contentWindow.document;
  5624. }catch(e){
  5625. returnFalse("Stop as cors");
  5626. return;
  5627. }
  5628.  
  5629. let waitTime=200,checkEval;
  5630. if(ruleParser.curSiteRule.waitElement){
  5631. checkEval = doc => {
  5632. return ruleParser.waitElement(doc);
  5633. };
  5634. }else if(ruleParser.curSiteRule.wait){
  5635. if(isNaN(ruleParser.curSiteRule.wait)){
  5636. try{
  5637. checkEval=(typeof _unsafeWindow.pagetualWait=='undefined') ? Function("doc", '"use strict";' + ruleParser.curSiteRule.wait) : _unsafeWindow.pagetualWait;
  5638. }catch(e){
  5639. debug(e);
  5640. }
  5641. }else{
  5642. waitTime=ruleParser.curSiteRule.wait;
  5643. }
  5644. }
  5645.  
  5646. if(!orgPage){
  5647. if(!loadmoreEnd){
  5648. loadmoreBtn=getLoadMore(iframeDoc);
  5649. if(loadmoreBtn && isVisible(loadmoreBtn, iframeDoc.defaultView)){
  5650. emuClick(loadmoreBtn);
  5651. let intv=setInterval(()=>{
  5652. loadmoreBtn=getLoadMore(iframeDoc);
  5653. if(!loadmoreBtn || !document.body.contains(loadmoreBtn) || !isVisible(loadmoreBtn, iframeDoc.defaultView)){
  5654. clearInterval(intv);
  5655. loadmoreEnd=true;
  5656. setTimeout(()=>{
  5657. checkPage();
  5658. },500);
  5659. }else if(isInViewPort(loadmoreBtn)){
  5660. emuClick(loadmoreBtn);
  5661. }
  5662. },200);
  5663. return;
  5664. }else{
  5665. loadmoreEnd=true;
  5666. }
  5667. }
  5668. if(checkEval && !checkEval(iframeDoc)){
  5669. waitTimes=10;
  5670. setTimeout(()=>{
  5671. checkPage();
  5672. },waitTime);
  5673. return;
  5674. }else {
  5675. nextLink = await ruleParser.getNextLink(iframeDoc);
  5676. pageEle = ruleParser.getPageElement(iframeDoc, iframeDoc.defaultView, true);
  5677. if (!pageEle || pageEle.length==0 || !nextLink) {
  5678. if (waitTimes-- > 0) {
  5679. setTimeout(() => {
  5680. checkPage();
  5681. }, waitTime);
  5682. return;
  5683. }
  5684. }
  5685. }
  5686. orgPage=pageEle;
  5687. if(!orgPage || orgPage.length==0){
  5688. returnFalse("Stop as no page when emu");
  5689. return;
  5690. }
  5691. if(orgPage[0].tagName=="UL")orgPage=orgPage[0].children;
  5692. if(nextLink){
  5693. orgPage=orgPage[parseInt(orgPage.length/2)];
  5694. if(orgPage.tagName=="IMG"){
  5695. if (!ruleParser.curSiteRule.lazyImgSrc) ruleParser.curSiteRule.lazyImgSrc = "0";
  5696. if (orgPage.src) {
  5697. orgContent = orgPage.src;
  5698. } else {
  5699. setTimeout(()=>{
  5700. checkPage();
  5701. },500);
  5702. return;
  5703. }
  5704. }else{
  5705. orgContent=orgPage.innerHTML;
  5706. }
  5707. preContent=orgContent;
  5708. if(!isVisible(nextLink, iframeDoc.defaultView)){
  5709. returnFalse("Stop as next hide when emu");
  5710. }else{
  5711. emuClick(nextLink);
  5712. setTimeout(()=>{
  5713. checkPage();
  5714. },500);
  5715. }
  5716. }else{
  5717. returnFalse("Stop as no next when emu");
  5718. }
  5719. return;
  5720. }
  5721. nextLink = nextLink || await ruleParser.getNextLink(iframeDoc);
  5722. if(!nextLink){
  5723. if(waitTimes-->0){
  5724. setTimeout(()=>{
  5725. checkPage();
  5726. },waitTime);
  5727. return;
  5728. }
  5729. }
  5730. if(times++ > 200){
  5731. returnFalse("Stop as timeout when emu");
  5732. return;
  5733. }
  5734. let eles=ruleParser.getPageElement(iframeDoc, iframeDoc.defaultView, true),checkItem;
  5735. if(eles && eles.length>0){
  5736. checkItem=eles;
  5737. if(eles[0].tagName=="UL")checkItem=eles[0].children;
  5738. checkItem=checkItem[parseInt(checkItem.length/2)];
  5739. }
  5740. if(!checkItem || (checkEval && !checkEval(iframeDoc))){
  5741. setTimeout(()=>{
  5742. checkPage();
  5743. },waitTime);
  5744. }else{
  5745. let checkInner;
  5746. if (checkItem.tagName == "IMG") {
  5747. if (checkItem.src) {
  5748. checkInner = checkItem.src;
  5749. } else {
  5750. setTimeout(() => {
  5751. checkPage();
  5752. }, waitTime);
  5753. return;
  5754. }
  5755. }else{
  5756. checkInner=checkItem.innerHTML;
  5757. }
  5758. if(orgPage!=checkItem || checkInner!=preContent){
  5759. changed=true;
  5760. orgPage=checkItem;
  5761. preContent=checkInner;
  5762. setTimeout(()=>{
  5763. checkPage();
  5764. },waitTime);
  5765. }else if(changed){
  5766. times = 0;
  5767. if (orgContent == preContent) {
  5768. returnFalse("Stop as same content");
  5769. } else {
  5770. callback(iframeDoc, eles);
  5771. }
  5772. }else{
  5773. if (times % 10 === 1) {
  5774. emuClick(nextLink);
  5775. }
  5776. setTimeout(()=>{
  5777. checkPage();
  5778. },waitTime);
  5779. }
  5780. }
  5781. }
  5782. if(!emuIframe){
  5783. let loaded=false;
  5784. emuIframe = document.createElement('iframe');
  5785. emuIframe.name = 'pagetual-iframe';
  5786. if(ruleParser.curSiteRule.sandbox!=false){
  5787. emuIframe.sandbox="allow-same-origin allow-scripts allow-popups allow-forms";
  5788. }
  5789. emuIframe.width = '100%';
  5790. emuIframe.height = '100';
  5791. emuIframe.frameBorder = '0';
  5792. 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;';
  5793. emuIframe.addEventListener("load", e => {
  5794. setTimeout(() => {
  5795. try {
  5796. iframeDoc = emuIframe.contentDocument || emuIframe.contentWindow.document;
  5797. } catch(e) {
  5798. returnFalse("Stop as cors");
  5799. return;
  5800. }
  5801. let code = ruleParser.curSiteRule.init;
  5802. if (code) {
  5803. try {
  5804. Function('doc','win','iframe','"use strict";' + code)(iframeDoc, iframeDoc.defaultView, emuIframe);
  5805. } catch(e) {
  5806. debug(e);
  5807. }
  5808. }
  5809. if (loaded) return;
  5810. loaded = true;
  5811. checkPage();
  5812. },500);
  5813. });
  5814. if (!lastActiveUrl) lastActiveUrl=location.href;
  5815. emuIframe.src = lastActiveUrl;
  5816. document.body.appendChild(emuIframe);
  5817. }else{
  5818. if (emuIframe.src != lastActiveUrl) emuIframe.src = lastActiveUrl;
  5819. checkPage();
  5820. }
  5821. }
  5822.  
  5823. var scrollToResizeInited = false;
  5824. var resizePool = [];
  5825. var scrollingToResize = false;
  5826.  
  5827. function scrollToResize(e) {
  5828. if (scrollingToResize) return;
  5829. else {
  5830. scrollingToResize = true;
  5831. let fitWidth = ruleParser.curSiteRule.fitWidth !== false;
  5832. let resizeHandler = () => {
  5833. resizePool.forEach(resizeArr => {
  5834. let iframe = resizeArr[1]();
  5835. let frameDoc = resizeArr[2]();
  5836. if(ruleParser.curSiteRule.singleUrl || forceState === 2){
  5837. iframe.style.height = (frameDoc.body.scrollHeight || frameDoc.body.offsetHeight) + "px";
  5838. iframe.style.minHeight = iframe.style.height;
  5839. iframe.style.width = "100%";
  5840. frameDoc.documentElement.scrollTop = 0;
  5841. frameDoc.documentElement.scrollLeft = 0;
  5842. }else{
  5843. let pageEle = resizeArr[0]();
  5844. if(pageEle){
  5845. let targetElement = pageEle[0];
  5846. if (!targetElement) return;
  5847. if(pageEle.length > 1){
  5848. targetElement = targetElement.parentNode;
  5849. }
  5850. let scrollHeight = targetElement.scrollHeight || targetElement.offsetHeight;
  5851. if(!scrollHeight || parseInt(iframe.style.height)==scrollHeight) return;
  5852. iframe.style.height=(scrollHeight+1)+"px";
  5853. let scrollTop = 0, scrollLeft = 0;
  5854. frameDoc.body.scrollTop = 0;
  5855. frameDoc.body.scrollLeft = 0;
  5856. while(targetElement && targetElement.offsetParent){
  5857. targetElement.offsetParent.scrollTop = targetElement.offsetTop;
  5858. if(targetElement.offsetParent.scrollTop == 0){
  5859. scrollTop += targetElement.offsetTop;
  5860. }
  5861. if(fitWidth){
  5862. targetElement.offsetParent.scrollLeft = targetElement.offsetLeft;
  5863. if(targetElement.offsetParent.scrollLeft == 0){
  5864. scrollLeft += targetElement.offsetLeft;
  5865. }
  5866. }
  5867. targetElement = targetElement.offsetParent;
  5868. }
  5869. frameDoc.documentElement.scrollTop = scrollTop;
  5870. frameDoc.documentElement.scrollLeft = scrollLeft;
  5871. if (frameDoc.documentElement.scrollTop == 0 && frameDoc.documentElement.scrollLeft == 0) {
  5872. frameDoc.body.scrollTop += scrollTop;
  5873. frameDoc.body.scrollLeft += scrollLeft;
  5874. }
  5875. if(!fitWidth && iframe.style.marginLeft == '0px'){
  5876. iframe.style.width = "100vw";
  5877. iframe.style.marginLeft = -iframe.getBoundingClientRect().left + "px";
  5878. }
  5879. }
  5880. }
  5881. });
  5882. };
  5883. setTimeout(() => {
  5884. scrollingToResize = false;
  5885. resizeHandler();
  5886. }, 200);
  5887. resizeHandler();
  5888. }
  5889. }
  5890.  
  5891. function forceIframe(url, callback) {
  5892. url = url.indexOf('=') == -1 ? url.replace(/#[^#]*/,"") : url;
  5893. let curIframe = document.createElement('iframe'), iframeDoc, isloaded = false, inAction = true;
  5894. let loadedHandler = () => {
  5895. inAction = false;
  5896. if (isloaded) return;
  5897. isloaded = true;
  5898. ruleParser.insertPage(iframeDoc, [], url, null, true);
  5899. callback(curIframe);
  5900. let getIframe = () => {
  5901. return curIframe;
  5902. };
  5903. let getFrameDoc = () => {
  5904. return iframeDoc;
  5905. };
  5906. if (ruleParser.curSiteRule.singleUrl) {
  5907. resizePool.push([() => {}, getIframe, getFrameDoc]);
  5908. } else {
  5909. let pageElement = ruleParser.getPageElement(iframeDoc,iframeDoc.defaultView);
  5910. let getPageEle = () => {
  5911. if (!pageElement || pageElement.length === 0) {
  5912. pageElement = ruleParser.getPageElement(iframeDoc,iframeDoc.defaultView);
  5913. }
  5914. return pageElement;
  5915. };
  5916. resizePool.push([getPageEle, getIframe, getFrameDoc]);
  5917. }
  5918. scrollToResize();
  5919. };
  5920. curIframe.name = 'pagetual-iframe';
  5921. curIframe.sandbox = "allow-same-origin allow-scripts allow-popups allow-forms";
  5922. curIframe.frameBorder = '0';
  5923. curIframe.scrolling = "no";
  5924. 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;';
  5925. curIframe.addEventListener("load", e => {
  5926. try {
  5927. iframeDoc = curIframe.contentDocument || curIframe.contentWindow.document;
  5928. } catch(e) {
  5929. debug("Stop as cors");
  5930. isPause = true;
  5931. callback(false);
  5932. return;
  5933. }
  5934. let css = ruleParser.curSiteRule.css || rulesData.customCss;
  5935. if (css) {
  5936. css = css.replace(/^inIframe:/, "");
  5937. let styleEle=iframeDoc.createElement("style");
  5938. styleEle.innerHTML=css;
  5939. iframeDoc.head.appendChild(styleEle);
  5940. }
  5941. loadedHandler();
  5942. let code = ruleParser.curSiteRule.init;
  5943. if (code) {
  5944. try {
  5945. Function('doc','win','iframe','"use strict";' + code)(iframeDoc,iframeDoc.defaultView,curIframe);
  5946. } catch(e) {
  5947. debug(e);
  5948. }
  5949. }
  5950. });
  5951. let checkTimes = 0, findPageEle = false;
  5952. let forceRefresh = e => {
  5953. if (inAction || !iframeDoc) return;
  5954. inAction = true;
  5955. let foundNext = () => {
  5956. document.removeEventListener("scroll", forceRefresh);
  5957. }
  5958. setTimeout(async () => {
  5959. inAction = false;
  5960. if (!ruleParser.nextLinkHref) {
  5961. checkTimes++;
  5962. await ruleParser.getNextLink(iframeDoc);
  5963. if (ruleParser.nextLinkHref) {
  5964. foundNext();
  5965. } else if (checkTimes >= 10) {
  5966. foundNext();
  5967. } else if (checkTimes >= 3 && !findPageEle) {
  5968. let pageElement = ruleParser.getPageElement(iframeDoc, iframeDoc.defaultView);
  5969. if (!pageElement) {
  5970. inAction = true;
  5971. curIframe.contentWindow.location.reload();
  5972. } else {
  5973. findPageEle = true;
  5974. }
  5975. }
  5976. } else {
  5977. foundNext();
  5978. }
  5979. },50);
  5980. };
  5981. document.addEventListener("scroll", forceRefresh);
  5982. curIframe.src = url;
  5983. let insert = ruleParser.getInsert();
  5984. if (ruleParser.curSiteRule.singleUrl || forceState == 2) {
  5985. document.body.appendChild(loadingDiv);
  5986. document.body.appendChild(curIframe);
  5987. } else {
  5988. ruleParser.insertElement(curIframe);
  5989. }
  5990.  
  5991. if (!scrollToResizeInited) {
  5992. scrollToResizeInited = true;
  5993. document.addEventListener("scroll", scrollToResize);
  5994. }
  5995. return curIframe;
  5996. }
  5997.  
  5998. function loadPageOver(){
  5999. isLoading = false;
  6000. stopScroll = true;
  6001. let dist = distToBottom();
  6002. let rate = (ruleParser.curSiteRule.rate || rulesData.rate || 1);
  6003. if (rate != 1 && !clickMode) {
  6004. setTimeout(() => {
  6005. if (dist < bottomGap) {
  6006. nextPage();
  6007. }
  6008. }, 1);
  6009. }
  6010. setTimeout(() => {stopScroll = false}, 300);
  6011. if(loadingDiv.parentNode){
  6012. loadingDiv.parentNode.removeChild(loadingDiv);
  6013. }
  6014. }
  6015.  
  6016. function checkAutoLoadNum() {
  6017. if (autoLoadNum >= 0) {
  6018. if (autoLoadNum != 0 && --autoLoadNum == 0) {
  6019. autoLoadNum = -1;
  6020. } else {
  6021. setTimeout(() => nextPage(), 1);
  6022. }
  6023. }
  6024. }
  6025.  
  6026. var tryTimes = 0;
  6027. async function nextPage() {
  6028. if (typeof ruleParser.curSiteRule.manualMode=='undefined' ? rulesData.manualMode : ruleParser.curSiteRule.manualMode) return;
  6029. if (clickMode) return;
  6030. if (isPause || isLoading || forceState==1) return;
  6031. if (ruleParser.curSiteRule.delay) {
  6032. try {
  6033. let checkDelay = ((typeof _unsafeWindow.pagetualDelay=='undefined') ? Function('"use strict";' + ruleParser.curSiteRule.delay) : _unsafeWindow.pagetualDelay)();
  6034. if (!checkDelay) return;
  6035. } catch(e) {
  6036. debug(e);
  6037. }
  6038. }
  6039. let nextLink = ruleParser.nextLinkHref;
  6040. if (!nextLink) {
  6041. if (curPage == 1) {
  6042. await ruleParser.getNextLink(document);
  6043. nextLink = ruleParser.nextLinkHref;
  6044. }
  6045. if (!nextLink) {
  6046. isLoading = true;
  6047. if (curPage == 1 && (ruleParser.curSiteRule.pinUrl || tryTimes++ <= 10)) {
  6048. setTimeout(() => {isLoading = false}, 500);
  6049. }
  6050. return;
  6051. }
  6052. }
  6053. let pvGallery = document.querySelector("span.pv-gallery-container");
  6054. if (pvGallery && pvGallery.style.display != "none") return;
  6055. let insert = ruleParser.getInsert();
  6056. if (insert) {
  6057. if (curPage == 1) {
  6058. /*window.postMessage({
  6059. insert: geneSelector(ruleParser.curSiteRule.insertPos == 2 ? insert : insert.parentNode, true),
  6060. command: 'pagetual.insert'
  6061. }, '*');*/
  6062. }
  6063. let isJs = ruleParser.curSiteRule.action == 3 || /^(javascript|#)/.test(nextLink.replace(location.href,""));
  6064. if (!isJs) {
  6065. emuIframe = null;
  6066. lastActiveUrl = nextLink;
  6067. if (location.protocol == "https:" && /^http:/.test(nextLink)) {
  6068. nextLink = nextLink.replace(/^http/, "https");
  6069. }
  6070. }
  6071. isLoading = true;
  6072. ruleParser.insertElement(loadingDiv);
  6073. let parent = loadingDiv.parentNode;
  6074. if (parent.tagName == "TBODY") {
  6075. parent = parent.parentNode;
  6076. }
  6077. if(parent.tagName == "TABLE"){
  6078. parent.parentNode.appendChild(loadingDiv);
  6079. }
  6080. loadingDiv.style.cssText = loadingCSS;
  6081. if (curPage == 1 && isJs && ruleParser.curSiteRule.singleUrl) {
  6082. loadingDiv.style.display = "none";
  6083. }
  6084. let sleep = ruleParser.curSiteRule.sleep || 0;
  6085. setTimeout(() => {
  6086. if (ruleParser.curSiteRule.pageElementByJs) {
  6087. var over = eles => {
  6088. loadPageOver();
  6089. if (urlChanged || isPause) return;
  6090. if (eles) {
  6091. ruleParser.insertPage(document, eles, nextLink, () => {
  6092. createPageBar(nextLink);
  6093. }, true);
  6094. checkAutoLoadNum();
  6095. } else {
  6096. debug("Stop as no page when get by js");
  6097. isPause = true;
  6098. }
  6099. };
  6100. try {
  6101. ((typeof _unsafeWindow.pagetualPageElementByJs == 'undefined') ? Function("over",'"use strict";' + ruleParser.curSiteRule.pageElementByJs) : _unsafeWindow.pagetualPageElementByJs)(over);
  6102. } catch(e) {
  6103. debug(e);
  6104. }
  6105. } else if ((forceState == 2 || ruleParser.curSiteRule.action == 2) && !isJs) {
  6106. forceIframe(nextLink, (iframe) => {
  6107. loadPageOver();
  6108. if (urlChanged || isPause) return;
  6109. let pageBar = createPageBar(nextLink);
  6110. if (pageBar && iframe) iframe.parentNode.insertBefore(pageBar, iframe);
  6111. checkAutoLoadNum();
  6112. });
  6113. } else if ((forceState == 3 || ruleParser.curSiteRule.action == 1) && !isJs) {
  6114. requestFromIframe(nextLink, (doc, eles) => {
  6115. loadPageOver();
  6116. if (urlChanged || isPause) return;
  6117. if (eles) {
  6118. ruleParser.insertPage(doc, eles, nextLink, () => {
  6119. createPageBar(nextLink);
  6120. }, true);
  6121. checkAutoLoadNum();
  6122. }
  6123. });
  6124. }else{
  6125. if(!isJs){
  6126. requestDoc(nextLink, (eles)=>{
  6127. loadPageOver();
  6128. if (urlChanged || isPause) return;
  6129. if (eles) {
  6130. createPageBar(nextLink);
  6131. checkAutoLoadNum();
  6132. }
  6133. });
  6134. }else{
  6135. emuPage((doc, eles)=>{
  6136. loadPageOver();
  6137. if (urlChanged || isPause) return;
  6138. if (eles) {
  6139. ruleParser.insertPage(doc, eles, "", ()=>{
  6140. createPageBar(nextLink);
  6141. }, true);
  6142. checkAutoLoadNum();
  6143. }
  6144. });
  6145. }
  6146. }
  6147. },sleep);
  6148. }
  6149. }
  6150.  
  6151. function init() {
  6152. initRules(() => {
  6153. initPage();
  6154. });
  6155. }
  6156.  
  6157. function visibilitychangeHandler() {
  6158. document.removeEventListener('visibilitychange', visibilitychangeHandler);
  6159. init();
  6160. }
  6161.  
  6162. setTimeout(() => {
  6163. if (document.hidden) {
  6164. document.addEventListener('visibilitychange', visibilitychangeHandler);
  6165. } else {
  6166. init();
  6167. }
  6168. },100);
  6169. })();