东方永页机

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

当前为 2022-10-02 提交的版本,查看 最新版本

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

QingJ © 2025

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