東方永頁機

自動翻頁脚本 - 自動加載並拼接下一分頁內容,支持任意網頁

目前為 2022-09-12 提交的版本,檢視 最新版本

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