东方永页机

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

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

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

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址