Greasy Fork 还支持 简体中文。

東方永頁機

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

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

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