东方永页机

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

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

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