东方永页机

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

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

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