东方永页机

自动翻页脚本 - 自动加载并拼接下一分页内容,支持任意网页

当前为 2022-09-18 提交的版本,查看 最新版本

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