东方永页机

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

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

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

QingJ © 2025

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