东方永页机

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

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

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