东方永页机

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

当前为 2022-08-18 提交的版本,查看 最新版本

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

QingJ © 2025

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