东方永页机

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

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

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