东方永页机

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

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