东方永页机

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

目前为 2022-09-24 提交的版本。查看 最新版本

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