东方永页机

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

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

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