东方永页机

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

当前为 2022-06-25 提交的版本,查看 最新版本

  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.26.6
  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 *://hoothin.github.io/PagetualGuide/*
  98. // @exclude *://wenku.baidu.com/view/*
  99. // @connect *
  100. // ==/UserScript==
  101.  
  102. (function() {
  103. 'use strict';
  104.  
  105. if (window.name === 'pagetual-iframe' || (window.frameElement && window.frameElement.name === 'pagetual-iframe')) {
  106. var domloaded = function (){
  107. window.scroll(window.scrollX, 999999);
  108. window.parent.postMessage('pagetual-iframe:DOMLoaded', '*');
  109. };
  110. if(window.opera){
  111. document.addEventListener('DOMContentLoaded', domloaded, false);
  112. } else {
  113. domloaded();
  114. }
  115. return;
  116. }
  117.  
  118. if(window.top != window.self){
  119. try{
  120. if (top.location.hostname != window.location.hostname || window.top != window.parent) {
  121. return;
  122. }
  123. }catch(e){
  124. return;
  125. }
  126. }
  127.  
  128. const lang = navigator.appName=="Netscape"?navigator.language:navigator.userLanguage;
  129. let config={};
  130. switch (lang){
  131. case "zh-CN":
  132. case "zh-SG":
  133. config={
  134. enableDebug:"调试模式,输出信息至控制台",
  135. disable:"暂时禁用",
  136. disableSite:"切换禁用状态",
  137. disableSiteTips:"已在此站禁用",
  138. enableSiteTips:"已在此站启用",
  139. enable:"启用翻页",
  140. toTop:"回到顶部",
  141. toBottom:"前往页尾",
  142. current:"当前页",
  143. forceIframe:"强制拼接",
  144. cancelForceIframe:"取消强制拼接",
  145. configure:"打开配置页",
  146. firstUpdate:"点击此处初始化规则",
  147. update:"更新规则",
  148. click2update:"点击立即更新规则",
  149. loadNow:"立即翻页",
  150. loadConfirm:"要翻几页?(0为不间断)",
  151. noNext:"没有找到下一页,请新建规则",
  152. passSec:"更新于 #t# 秒前",
  153. passMin:"更新于 #t# 分钟前",
  154. passHour:"更新于 #t# 小时前",
  155. passDay:"更新于 #t# 天前",
  156. cantDel:"无法删除内置规则",
  157. confirmDel:"是否确认要删除此规则?",
  158. updateSucc:"更新成功",
  159. beginUpdate:"正在更新,请耐心等待,不要关闭页面",
  160. customUrls:"导入规则url,一行一条,AutoPagerize 格式规则需要以\"0|\"开头",
  161. customRules:"输入【东方永页机】格式的自定义规则",
  162. save:"保存设置",
  163. loadingText:"少女祈祷中...",
  164. opacity:"不透明值",
  165. hideBar:"隐藏分页隔条",
  166. dbClick2Stop:"空白处双击暂停翻页",
  167. sortTitle:"排序在下次更新规则后生效",
  168. autoRun:"自动启用,否则为白名单模式",
  169. inputPageNum:"输入页码跳转",
  170. enableHistory:"翻页后写入历史记录",
  171. initRun:"打开页面后立即尝试翻页,否则滚动至页尾再翻页",
  172. preload:"翻页前预读下一页,加速浏览",
  173. click2ImportRule:"点击下方添加特殊规则库,并静待更新成功:",
  174. forceAllBody:"是否拼接整个页面?",
  175. openInNewTab:"使拼接页面的内容在新页面打开",
  176. importSucc:"导入成功",
  177. editCurrent:"自定义此站规则",
  178. editBlacklist:"编辑黑名单网址,一行一条,支持? *通配符",
  179. upBtnImg:"回到页首图标",
  180. downBtnImg:"前往页尾图标",
  181. dbClick2StopCtrl:"Ctrl 键",
  182. dbClick2StopAlt:"Alt 键",
  183. dbClick2StopShift:"Shift 键",
  184. dbClick2StopMeta:"Meta 键",
  185. dbClick2StopKey:"快捷键"
  186. };
  187. break;
  188. case "zh-TW":
  189. case "zh-HK":
  190. config={
  191. enableDebug:"調試模式,輸出信息至控制台",
  192. disable:"暫時禁用",
  193. disableSite:"切換禁用狀態",
  194. disableSiteTips:"已在此站禁用",
  195. enableSiteTips:"已在此站啟用",
  196. enable:"啟用翻頁",
  197. toTop:"回到頂部",
  198. toBottom:"前往頁尾",
  199. current:"當前頁",
  200. forceIframe:"強制拼接",
  201. cancelForceIframe:"取消强制拼接",
  202. configure:"打開配置頁",
  203. firstUpdate:"點擊此處初始化規則",
  204. update:"更新規則",
  205. click2update:"點擊立即更新規則",
  206. loadNow:"立即翻頁",
  207. loadConfirm:"要翻几頁?(0為不間斷)",
  208. noNext:"沒有找到下一頁,請新建規則",
  209. passSec:"更新于 #t# 秒前",
  210. passMin:"更新于 #t# 分鐘前",
  211. passHour:"更新于 #t# 小時前",
  212. passDay:"更新于 #t# 天前",
  213. cantDel:"無法刪除内置規則",
  214. confirmDel:"是否確認要刪除此規則?",
  215. updateSucc:"更新成功",
  216. beginUpdate:"正在更新,請稍候",
  217. customUrls:"導入規則url,一行一條,AutoPagerize 格式規則需要以\"0|\"開頭",
  218. customRules:"輸入【東方永頁機】格式的自定義規則",
  219. save:"存儲設置",
  220. loadingText:"少女祈禱中...",
  221. opacity:"不透明值",
  222. hideBar:"隱藏分頁隔條",
  223. dbClick2Stop:"空白處雙擊暫停翻頁",
  224. sortTitle:"排序在下次更新規則後生效",
  225. autoRun:"自動啓用,否則為白名單模式",
  226. inputPageNum:"輸入頁碼跳轉",
  227. enableHistory:"翻頁后寫入歷史記錄",
  228. initRun:"打開頁面后立即嘗試翻頁,否則滾動至頁尾再翻頁",
  229. preload:"翻頁前預讀下一頁,加速瀏覽",
  230. click2ImportRule:"點擊下方添加特殊規則庫,并靜待更新成功:",
  231. forceAllBody:"是否拼接整個頁面?",
  232. openInNewTab:"使拼接頁面的内容在新頁面打開",
  233. importSucc:"導入成功",
  234. editCurrent:"自定義此站規則",
  235. editBlacklist:"編輯黑名單網址,一行一條,支持? *通配符",
  236. upBtnImg:"回到頁首圖標",
  237. downBtnImg:"前往頁尾圖標",
  238. dbClick2StopCtrl:"Ctrl 鍵",
  239. dbClick2StopAlt:"Alt 鍵",
  240. dbClick2StopShift:"Shift 鍵",
  241. dbClick2StopMeta:"Meta 鍵",
  242. dbClick2StopKey:"快捷鍵"
  243. };
  244. break;
  245. case "ja":
  246. config = {
  247. enableDebug:"デバッグモード",
  248. disable: "一時的に無効にする",
  249. disableSite:"無効状態の切り替え",
  250. disableSiteTips:"このサイトで既に無効になっています",
  251. enableSiteTips:"このサイトで既に有効になっています",
  252. enable: "ページめくりを有効にする",
  253. toTop: "トップに戻る",
  254. toBottom: "ページの下部に移動",
  255. current: "現在のページ",
  256. forceIframe: "強制ステッチ",
  257. cancelForceIframe: "強制ステッチをキャンセル",
  258. configure: "設定ページを開く",
  259. firstUpdate:"ここをクリックしてルールを初期化します",
  260. update: "更新ルール",
  261. click2update:"今すぐルールを更新してください",
  262. loadNow:"今すぐページをめくる",
  263. loadConfirm:"数ページめくりたいですか?(0は途切れない)",
  264. noNext:"次のページが見つかりません、新しいルールを作成してください",
  265. passSec: "#t#秒前に更新",
  266. passMin: "#t#分前に更新",
  267. passHour: "#t#時間前に更新",
  268. passDay: "#t#日前に更新",
  269. cantDel: "組み込みルールを削除できません",
  270. confirmDel: "このルールを削除してもよろしいですか?",
  271. updateSucc: "更新に成功しました",
  272. beginUpdate: "更新中、お待ちください",
  273. customUrls: "インポートルールのURL、1行に1つ、AutoPagerizeフォーマットルールは\"0|\"で始まる必要があります",
  274. customRules: "【東方永頁機】の形式でカスタムルールを入力してください",
  275. save: "設定を保存",
  276. loadingText: "少女祈祷中...",
  277. opacity:"不透明値",
  278. hideBar:"ページ区切り文字を非表示にします",
  279. dbClick2Stop:"空白部分をダブルクリックしてページめくりを一時停止します",
  280. sortTitle:"並べ替えは、次のルールの更新後に有効になります",
  281. autoRun:"自動的に有効",
  282. inputPageNum:"ジャンプするページ番号を入力",
  283. enableHistory:"ページめくり後の履歴を書く",
  284. initRun:"Webページを開いた直後にページをめくる",
  285. preload:"事前に次のページを読む",
  286. click2ImportRule:"以下をクリックして、ルールベースを追加します:",
  287. forceAllBody:"フルページ埋め込み?",
  288. openInNewTab:"スプライスされたページのコンテンツを新しいページで開きます",
  289. importSucc:"インポート完了",
  290. editCurrent:"現在のルールの編集",
  291. editBlacklist:"ブラックリストのURLを編集し、1行ずつ、サポート? *ワイルドカード",
  292. upBtnImg:"トップアイコンに戻る",
  293. downBtnImg:"フッターアイコンに移動",
  294. dbClick2StopCtrl:"Ctrlキー",
  295. dbClick2StopAlt:"Altキー",
  296. dbClick2StopShift:"Shiftキー",
  297. dbClick2StopMeta:"Metaキー",
  298. dbClick2StopKey:"Shortcutキー"
  299. };
  300. break;
  301. default:
  302. config={
  303. enableDebug:"Enable debug output",
  304. disable:"Disable",
  305. disableSite:"Toggle disabled state",
  306. disableSiteTips:"Disabled on this site",
  307. enableSiteTips:"Enabled on this site",
  308. enable:"Enable",
  309. toTop:"To Top",
  310. toBottom:"To Bottom",
  311. current:"Current Page",
  312. forceIframe:"Force to join",
  313. cancelForceIframe:"Cancel Force join",
  314. configure:"Configure",
  315. firstUpdate:"Click here to initialize the rules",
  316. update:"Update rules",
  317. click2update:"Click to update rules from url now",
  318. loadNow:"Load next now",
  319. loadConfirm:"How much pages do you want to load? (0 means infinite)",
  320. noNext:"No next link found, please create a new rule",
  321. passSec:"Updated #t# seconds ago",
  322. passMin:"Updated #t# minutes ago",
  323. passHour:"Updated #t# hours ago",
  324. passDay:"Updated #t# days ago",
  325. cantDel:"Can't delete buildin rules",
  326. confirmDel:"Are you sure you want to delete this rule?",
  327. updateSucc:"Update succeeded",
  328. beginUpdate:"Begin update, wait a minute please",
  329. customUrls:"Import rule url, One url per line, rules on AutoPagerize format need to start with \"0|\"",
  330. customRules:"Input custom rules with [Pagetual] format",
  331. save:"Save",
  332. loadingText:"Shojo Now Loading...",
  333. opacity:"Opacity",
  334. hideBar:"hide the paging spacer",
  335. dbClick2Stop:"Double-click on the blank space to pause",
  336. sortTitle:"Sorting takes effect after the next rule update",
  337. autoRun:"Auto run (black list mode)",
  338. inputPageNum:"Enter page number to jump",
  339. enableHistory:"Write history after page turning",
  340. initRun:"Turn pages immediately after opening",
  341. preload:"Preload next page for speeding up",
  342. click2ImportRule:"Click to import base rules link, then wait until the update is complete:",
  343. forceAllBody:"Join full body of page?",
  344. openInNewTab:"Open urls of additions in new tab",
  345. importSucc:"Import completed",
  346. editCurrent:"Edit rule for current",
  347. editBlacklist:"Edit the blacklist urls, line by line, Support ? * for wildcard",
  348. upBtnImg:"Icon of back to top",
  349. downBtnImg:"Icon of go to footer",
  350. dbClick2StopCtrl:"Ctrl key",
  351. dbClick2StopAlt:"Alt key",
  352. dbClick2StopShift:"Shift key",
  353. dbClick2StopMeta:"Meta key",
  354. dbClick2StopKey:"Shortcut key"
  355. };
  356. break;
  357. }
  358. var i18n=(name, param)=>{
  359. return config[name]?config[name].replace("#t#",param):name;
  360. };
  361.  
  362. var noRuleTest=false;
  363. var enableDebug=true;
  364. var debug=str=>{
  365. if(enableDebug){
  366. console.log(
  367. `%cPagetual v.${_GM_info.script.version}】 debug`,
  368. 'color: yellow;font-size: x-large;font-weight: bold;'
  369. );
  370. console.debug(str);
  371. }
  372. };
  373.  
  374. var _GM_xmlhttpRequest,_GM_registerMenuCommand,_GM_notification,_GM_addStyle,_GM_openInTab,_GM_info;
  375. if(typeof GM_xmlhttpRequest!='undefined'){
  376. _GM_xmlhttpRequest=GM_xmlhttpRequest;
  377. }else if(typeof GM!='undefined' && typeof GM.xmlHttpRequest!='undefined'){
  378. _GM_xmlhttpRequest=GM.xmlHttpRequest;
  379. }else{
  380. _GM_xmlhttpRequest=(f)=>{fetch(f.url).then(response=>response.text()).then(data=>{let res={response:data};f.onload(res)}).catch(f.onerror())};
  381. }
  382. if(typeof GM_registerMenuCommand!='undefined'){
  383. _GM_registerMenuCommand=GM_registerMenuCommand;
  384. }else if(typeof GM!='undefined' && typeof GM.registerMenuCommand!='undefined'){
  385. _GM_registerMenuCommand=GM.registerMenuCommand;
  386. }else{
  387. _GM_registerMenuCommand=(s,f)=>{};
  388. }
  389. if(typeof GM_info!='undefined'){
  390. _GM_info=GM_info;
  391. }else if(typeof GM!='undefined' && typeof GM.info!='undefined'){
  392. _GM_info=GM.info;
  393. }else{
  394. _GM_info={script:1};
  395. }
  396. if(typeof GM_notification!='undefined'){
  397. _GM_notification=GM_notification;
  398. }else if(typeof GM!='undefined' && typeof GM.notification!='undefined'){
  399. _GM_notification=GM.notification;
  400. }else{
  401. _GM_notification=(s)=>{showTips(s)};
  402. }
  403. if(typeof GM_openInTab!='undefined'){
  404. _GM_openInTab=GM_openInTab;
  405. }else if(typeof GM!='undefined' && typeof GM.openInTab!='undefined'){
  406. _GM_openInTab=GM.openInTab;
  407. }else{
  408. _GM_openInTab=(s,t)=>{window.open(s)};
  409. }
  410. if(typeof GM_addStyle!='undefined'){
  411. _GM_addStyle=GM_addStyle;
  412. }else if(typeof GM!='undefined' && typeof GM.addStyle!='undefined'){
  413. _GM_addStyle=GM.addStyle;
  414. }else{
  415. _GM_addStyle=cssStr=>{
  416. let styleEle=document.createElement("style");
  417. styleEle.innerHTML=cssStr;
  418. document.head.appendChild(styleEle);
  419. };
  420. }
  421. var _unsafeWindow=(typeof unsafeWindow=='undefined')?window:unsafeWindow;//兼容 ios userscripts 的寫法
  422. var storage={
  423. supportGM: typeof GM_getValue=='function' && typeof GM_getValue('a','b')!='undefined',
  424. supportGMPromise: typeof GM!='undefined' && typeof GM.getValue=='function' && typeof GM.getValue('a','b')!='undefined',
  425. mxAppStorage:(function(){
  426. try{
  427. return window.external.mxGetRuntime().storage;
  428. }catch(e){
  429. }
  430. })(),
  431. operaUJSStorage:(function(){
  432. try{
  433. return window.opera.scriptStorage;
  434. }catch(e){
  435. }
  436. })(),
  437. setItem:function(key,value){
  438. if(this.operaUJSStorage){
  439. this.operaUJSStorage.setItem(key,value);
  440. }else if(this.mxAppStorage){
  441. this.mxAppStorage.setConfig(key,value);
  442. }else if(this.supportGM){
  443. GM_setValue(key,value);
  444. if(value==="" && typeof GM_deleteValue!='undefined'){
  445. GM_deleteValue(key);
  446. }
  447. }else if(this.supportGMPromise){
  448. GM.setValue(key,value);
  449. if(value==="" && typeof GM!='undefined' && typeof GM.deleteValue!='undefined'){
  450. GM.deleteValue(key);
  451. }
  452. }else if(window.localStorage){
  453. window.localStorage.setItem(key,value);
  454. }
  455. },
  456. getItem:function(key,cb){
  457. var value;
  458. if(this.operaUJSStorage){
  459. value=this.operaUJSStorage.getItem(key);
  460. }else if(this.mxAppStorage){
  461. value=this.mxAppStorage.getConfig(key);
  462. }else if(this.supportGM){
  463. value=GM_getValue(key);
  464. }else if(this.supportGMPromise){
  465. value=GM.getValue(key).then(v=>{cb(v)});
  466. return;
  467. }else if(window.localStorage){
  468. value=window.localStorage.getItem(key);
  469. };
  470. cb(value);
  471. }
  472. };
  473. var rulesData={},ruleUrls,updateDate,configPage="https://github.com/hoothin/UserScripts/tree/master/Pagetual";
  474. var ruleImportUrlReg=/greasyfork\.org\/.*scripts\/438684[^\/]*(\/discussions|\/?$)|github\.com\/hoothin\/UserScripts\/(tree\/master\/Pagetual|issues)/i;
  475. var allOfBody="body>*";
  476. _GM_registerMenuCommand(i18n("configure"), ()=>{
  477. _GM_openInTab(configPage,{active:true});
  478. });
  479. _GM_registerMenuCommand(i18n("editCurrent"), ()=>{
  480. let editTemp;
  481. if(ruleParser.curSiteRule.url && !ruleParser.curSiteRule.singleUrl){
  482. editTemp=ruleParser.curSiteRule;
  483. }else{
  484. editTemp={
  485. name: document.title,
  486. url: "^"+location.origin.replace(/\./g,"\\."),
  487. pageElement: ruleParser.curSiteRule.pageElement||""
  488. };
  489. }
  490. rulesData.editTemp=editTemp;
  491. storage.setItem("rulesData", rulesData);
  492. _GM_openInTab(configPage,{active:true});
  493. });
  494.  
  495. function getElementByXpath(xpath, contextNode, doc){
  496. doc = doc || document;
  497. contextNode = contextNode || doc;
  498. try {
  499. var result = doc.evaluate(xpath, contextNode, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
  500. return result.singleNodeValue && result.singleNodeValue.nodeType === 1 && result.singleNodeValue;
  501. } catch (err) {
  502. throw new Error(`Invalid xpath: ${xpath}`);
  503. }
  504. }
  505.  
  506. function getAllElementsByXpath(xpath, contextNode, doc){
  507. doc = doc || document;
  508. contextNode = contextNode || doc;
  509. var result = [];
  510. try {
  511. var query = doc.evaluate(xpath, contextNode, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  512. for (var i = 0; i < query.snapshotLength; i++) {
  513. var node = query.snapshotItem(i);
  514. if (node.nodeType === 1) result.push(node);
  515. }
  516. } catch (err) {
  517. throw new Error(`Invalid xpath: ${xpath}`);
  518. }
  519. return result;
  520. }
  521.  
  522. class RuleParser {
  523. constructor() {
  524. this.hpRules=[];
  525. this.customRules=[];
  526. this.rules=[];
  527. this.pageDoc=document;
  528. this.nextLinkHref=null;
  529. this.nextTitle="";
  530. this.oldUrl="";
  531. this.curUrl=location.href;
  532. this.curSiteRule={};
  533. }
  534.  
  535. initSavedRules(callback){
  536. var self=this;
  537. storage.getItem("hpRules", hpRules=>{
  538. if(hpRules)self.hpRules=hpRules;
  539. storage.getItem("customRules", customRules=>{
  540. if(customRules)self.customRules=customRules;
  541. storage.getItem("rules", rules=>{
  542. if(rules)self.rules=rules;
  543. callback();
  544. });
  545. });
  546. });
  547. }
  548.  
  549. saveCurSiteRule(){
  550. if(!this.curSiteRule || !this.curSiteRule.url || this.curSiteRule.singleUrl || this.curSiteRule.url.length<13)return;
  551. this.hpRules=this.hpRules.filter(item=>{return item&&item.url!=this.curSiteRule.url});
  552. this.hpRules.unshift(this.curSiteRule);
  553. if(this.hpRules.length>30){
  554. this.hpRules.pop();
  555. }
  556. storage.setItem("hpRules", this.hpRules);
  557. }
  558.  
  559. requestJSON(url, callback){
  560. _GM_xmlhttpRequest({
  561. url: url,
  562. method: 'GET',
  563. timeout: 20000,
  564. onload: function(res) {
  565. let json=null;
  566. try{
  567. json=JSON.parse(res.response||res.responseText);
  568. }catch(e){
  569. debug(e);
  570. }
  571. callback(json);
  572. },
  573. onerror: function(e) {
  574. callback(null, e);
  575. },
  576. ontimeout: function(e) {
  577. callback(null, e);
  578. }
  579. });
  580. }
  581.  
  582. formatRule(item, type, from){
  583. switch(type){
  584. case 0:
  585. return {
  586. from:from,
  587. type:type,
  588. name:item.name,
  589. action:item.data.forceIframe=="true"?1:0,
  590. url:item.data.url,
  591. pageElement:item.data.pageElement,
  592. nextLink:item.data.nextLink,
  593. insert:item.data.insertBefore,
  594. insertPos:1,
  595. updatedAt:item.data.updated_at,
  596. css:item.data.Stylus+item.data.CSS,
  597. pageAction:item.data.bookmarklet
  598. };
  599. break;
  600. case 1:
  601. default:
  602. item.from=from;
  603. if(typeof(item.type) == "undefined")item.type=type;
  604. return item;
  605. break;
  606. }
  607. return null;
  608. }
  609.  
  610. addRuleByUrl(url, type, from, callback) {
  611. if(url.indexOf("?")==-1){
  612. url=url+"?"+Date.now();
  613. }else{
  614. url=url+"&"+Date.now();
  615. }
  616. this.requestJSON(url, (json,err)=>{
  617. if(!json){
  618. debug("Update "+url+" rules fail!");
  619. debug(err);
  620. }
  621. this.addRules(json, type, from);
  622. callback(json, err);
  623. });
  624. }
  625.  
  626. addRules(rules, type, from) {
  627. if(rules && rules.length>0){
  628. this.rules=this.rules.filter(item=>{return item.from!=from});
  629. rules.forEach(item=>{
  630. let rule=this.formatRule(item, type, from);
  631. if(rule){
  632. this.rules.unshift(rule);
  633. }
  634. });
  635. }
  636. }
  637.  
  638. getRule(callback) {
  639. if(noRuleTest){
  640. this.curSiteRule={};
  641. this.curSiteRule.url=location.origin+location.pathname;
  642. this.curSiteRule.singleUrl=true;
  643. callback();
  644. return;
  645. }
  646. if(this.curSiteRule && this.curSiteRule.url){
  647. return this.curSiteRule;
  648. }
  649. var self=this;
  650.  
  651. function setRule(r){
  652. self.curSiteRule=r;
  653. debug(r);
  654. callback();
  655. }
  656.  
  657. function ruleMatch(r){
  658. let pageElement,nextLink,insert;
  659. if(r.nextLink && r.nextLink!="0" && r.nextLink!=0){
  660. nextLink=r.type==0?getElementByXpath(r.nextLink):document.querySelector(r.nextLink);
  661. if(!nextLink)return false;
  662. }
  663. if(r.pageElement){
  664. pageElement=r.type==0?getElementByXpath(r.pageElement):document.querySelector(r.pageElement);
  665. if(!pageElement)return false;
  666. }
  667. if(r.insert){
  668. insert=r.type==0?getElementByXpath(r.insert):document.querySelector(r.insert);
  669. if(!insert)return false;
  670. }
  671. return true;
  672. }
  673.  
  674. function checkRule(r){
  675. let urlReg=new RegExp(r.url, "i");
  676. if(urlReg.test(location.href)){
  677. if(r.include){
  678. let include=r.type==0?getElementByXpath(r.include):document.querySelector(r.include);
  679. if(!include)return false;
  680. }
  681. if(r.exclude){
  682. let exclude=r.type==0?getElementByXpath(r.exclude):document.querySelector(r.exclude);
  683. if(exclude)return false;
  684. }
  685. if(r.wait){
  686. let waitTime=500,checkEval;
  687. if(isNaN(r.wait)){
  688. try{
  689. checkEval=(typeof _unsafeWindow.pagetualWait=='undefined') ? Function("doc",'"use strict";' + r.wait) : _unsafeWindow.pagetualWait;
  690. }catch(e){
  691. debug(e);
  692. }
  693. }else{
  694. waitTime=r.wait;
  695. }
  696. let checkReady=()=>{
  697. setTimeout(()=>{
  698. if(!ruleMatch(r) || (checkEval && !checkEval(document))){
  699. checkReady();
  700. }else{
  701. setRule(r);
  702. }
  703. },parseInt(waitTime));
  704. };
  705. checkReady();
  706. return true;
  707. }
  708. if(r.pinUrl){
  709. setRule(r);
  710. return true;
  711. }
  712. if(!ruleMatch(r)){
  713. return false;
  714. }
  715. setRule(r);
  716. return true;
  717. }
  718. return false;
  719. }
  720.  
  721. for(let i in this.hpRules){
  722. let rule=this.hpRules[i];
  723. if(!rule || !rule.url)continue;
  724. if(rule.singleUrl){
  725. if(location.origin+location.pathname==rule.url){
  726. setRule(rule);
  727. return;
  728. }
  729. continue;
  730. }
  731. if(checkRule(rule))return;
  732. }
  733. for(let i in this.customRules){
  734. let rule=this.customRules[i];
  735. if(!rule || !rule.url)continue;
  736. if(checkRule(rule))return;
  737. }
  738. let r=0;
  739. function searchByTime(){
  740. setTimeout(()=>{
  741. let end=r+50;
  742. end=end>self.rules.length?self.rules.length:end;
  743. for(;r<end;r++){
  744. let rule=self.rules[r];
  745. if(checkRule(rule))return;
  746. }
  747. if(end>=self.rules.length){
  748. self.curSiteRule={};
  749. self.curSiteRule.url=location.origin+location.pathname;
  750. self.curSiteRule.singleUrl=true;
  751. callback();
  752. return;
  753. }else{
  754. searchByTime();
  755. }
  756. },10);
  757. }
  758. searchByTime();
  759. }
  760.  
  761. geneSelector(ele){
  762. let selector=ele.tagName;
  763. //Google id class都是隨機。百度更過分,style script順序都是隨機的
  764. //if(ele.id) selector += '#' + ele.id;
  765. //if(ele.classList) selector += [].map.call(ele.classList,d=>'.'+d).join('');
  766. if(ele.tagName!="HTML" && ele.tagName!="BODY"){
  767. if(ele.className) selector += [].map.call(ele.classList,d=>'.'+d).join('');
  768. let parent = ele.parentElement;
  769. if(parent){
  770. selector = this.geneSelector(parent) + ' > ' + selector;
  771. if(!ele.className){
  772. let i,j=0;
  773. for(i=0;i<parent.children.length;i++){
  774. if(parent.children[i].tagName==ele.tagName){
  775. j++;
  776. if(parent.children[i]==ele){
  777. break;
  778. }
  779. }
  780. }
  781. selector += (parent.tagName=="HTML"?"":`:nth-of-type(${j})`);
  782. }
  783. }
  784. }
  785. return selector;
  786. }
  787.  
  788. getPageElement(doc, curWin, dontFind) {
  789. let pageElement=null;
  790. let self=this;
  791. let body=doc.body;
  792. if(this.curSiteRule.pageElement){
  793. pageElement=this.curSiteRule.type==0?getAllElementsByXpath(this.curSiteRule.pageElement,doc,doc):doc.querySelectorAll(this.curSiteRule.pageElement);
  794. }else if(!this.curSiteRule.singleUrl && this.curSiteRule.type==0){
  795. pageElement=[body];
  796. }
  797. if(this.curSiteRule.singleUrl && pageElement && pageElement.length>0 && pageElement[0].tagName=="TR"){
  798. let mainTr=this.insert.parentNode.querySelector('tr'),mainTdNum=0,newTdNum=0;
  799. [].forEach.call(mainTr.children, el=>{
  800. if(el.tagName=="TD" || el.tagName=="TH"){
  801. mainTdNum+=el.colSpan||1;
  802. }
  803. });
  804. [].forEach.call(pageElement[0].children, el=>{
  805. if(el.tagName=="TD" || el.tagName=="TH"){
  806. newTdNum+=el.colSpan||1;
  807. }
  808. });
  809. if(mainTdNum!=newTdNum){
  810. this.curSiteRule.pageElement=allOfBody;
  811. pageElement=[body];
  812. this.getInsert(true);
  813. }
  814. }
  815. if((this.curSiteRule.singleUrl || !this.curSiteRule.pageElement) && (!pageElement || pageElement.length==0) && curWin && !dontFind){
  816. if(!body)return null;
  817. let bodyHeight=parseInt(body.offsetHeight || body.scrollHeight);
  818. let curHeight=bodyHeight;
  819. let windowHeight=window.innerHeight || document.documentElement.clientHeight;
  820. let needCheckNext=(doc==document && this.initNext);
  821. function checkElement(ele){
  822. if(ele.childNodes && ele.childNodes.length==1)ele=ele.childNodes[0];
  823. if(ele.tagName=="PICTURE"){
  824. self.curSiteRule.pageElement=self.geneSelector(ele.parentNode)+">"+ele.tagName;
  825. debug(self.curSiteRule.pageElement);
  826. return [ele];
  827. }
  828. if(curHeight/bodyHeight<=0.25){
  829. self.curSiteRule.pageElement=allOfBody;
  830. debug(self.curSiteRule.pageElement);
  831. return [body];
  832. }
  833. if(ele.tagName=="FORM"){
  834. self.curSiteRule.pageElement=self.geneSelector(ele)+">*";
  835. debug(self.curSiteRule.pageElement);
  836. return ele.children;
  837. }
  838. if(ele.children.length==0 && !self.curSiteRule.pageElement){
  839. if(ele.parentNode.tagName=="P")ele=ele.parentNode;
  840. self.curSiteRule.pageElement=self.geneSelector(ele.parentNode)+">"+ele.tagName;
  841. debug(self.curSiteRule.pageElement);
  842. return [ele];
  843. }
  844. let i,maxHeight=curHeight*0.55,curMaxEle=null,curMaxArea=0,maxWidth=0;
  845. let isHori=true;
  846. let offsetTop=ele.children[0].offsetTop;
  847. for(i=1;i<ele.children.length;i++){
  848. if(ele.children[i].offsetTop!=offsetTop){
  849. isHori=false;
  850. break;
  851. }
  852. }
  853. for(i=0;i<ele.children.length;i++){
  854. let curNode=ele.children[i];
  855. if(curNode.tagName=="CANVAS")continue;
  856. if(curNode.tagName!="IMG" && /^\s*$/.test(curNode.innerText))continue;
  857. if(needCheckNext && !curNode.contains(self.initNext) && getElementTop(curNode)>windowHeight){
  858. continue;
  859. }
  860. let comStyle=curWin.getComputedStyle(curNode);
  861. let h=parseInt(curNode.offsetHeight || curNode.scrollHeight);
  862. let w=parseInt(curNode.scrollWidth);
  863. if(isNaN(h) || isNaN(w))continue;
  864. if(isHori && h<=50)continue;
  865. let a=h*w+h,moreChild=curNode.children[0];
  866. while(moreChild){
  867. comStyle=curWin.getComputedStyle(moreChild);
  868. let ch=parseInt(moreChild.offsetHeight || moreChild.scrollHeight);
  869. let cw=parseInt(moreChild.scrollWidth);
  870. if(h<ch)h=ch;
  871. if(moreChild.innerText!="" && !isNaN(ch) && !isNaN(cw)){
  872. a+=ch*cw;
  873. }
  874. moreChild=moreChild.nextElementSibling;
  875. }
  876. let isMax=false;
  877. if(isHori){
  878. if(maxWidth<w){
  879. isMax=true;
  880. }else if(maxWidth==w && curMaxArea<a){
  881. isMax=true;
  882. }
  883. }else{
  884. isMax=curMaxArea<a;
  885. }
  886. if(curMaxEle==null || isMax){
  887. if(h>0 || !isHori)curHeight=h;
  888. curMaxArea=a;
  889. maxWidth=w;
  890. curMaxEle=curNode;
  891. }
  892. }
  893. if(curMaxEle && (isHori || curHeight>maxHeight || (needCheckNext && curHeight>windowHeight && ele.contains(self.initNext)))){
  894. return checkElement(curMaxEle);
  895. }
  896. if(ele.tagName=="P" || ele.tagName=="BR")ele=ele.parentNode;
  897. if(ele.tagName=="TBODY"){
  898. self.curSiteRule.pageElement=self.geneSelector(ele)+">*";
  899. if(ele.children.length>0 && ele.children[0].querySelector("th")){
  900. self.curSiteRule.pageElement+=":not(:first-child)";
  901. }
  902. debug(self.curSiteRule.pageElement);
  903. return ele.children;
  904. }
  905. self.curSiteRule.pageElement=self.geneSelector(ele);
  906. if(ele.children.length>1){
  907. let hasText=false;
  908. for(let i in ele.childNodes){
  909. let child=ele.childNodes[i];
  910. if(child.nodeType==3 && child.nodeValue.trim()!=''){
  911. hasText=true;
  912. ele=[ele];
  913. break;
  914. }
  915. }
  916. if(!hasText){
  917. let middleChild=ele.children[parseInt(ele.children.length/2)];
  918. if((middleChild.style && middleChild.style.position=="absolute" && middleChild.style.left && middleChild.style.top) || ele.tagName=="UL" || curHeight==0){
  919. ele=[ele];
  920. }else{
  921. self.curSiteRule.pageElement+=">*";
  922. ele=ele.children;
  923. }
  924. }
  925. }else{
  926. ele=[ele];
  927. }
  928. debug(self.curSiteRule.pageElement);
  929. return ele;
  930. }
  931. pageElement=checkElement(body);
  932. //if(pageElement)this.saveCurSiteRule();
  933. }
  934. return pageElement;
  935. }
  936.  
  937. getPage(doc){
  938. if(typeof _unsafeWindow.Discourse!='undefined')return {};
  939. let canSave=false;//發現頁碼選擇器在其他頁對不上,還是別保存了
  940. let url=this.curUrl.replace("#!","").replace("index.php?","?");
  941. let _url=url.replace(/\.s?html?$/i,"");
  942. let pageNum=1,preStr="",afterStr="";
  943. let pageMatch1=url.match(/(.*[a-z\/\-_](?:p|page)?\/?)(\d+)(\.s?html?$|\/?$)/i);
  944. let pageMatch2=url.match(/(.*[\?&]p(?:age)?=)(\d+)($|[#&].*)/i);
  945. if(pageMatch1){
  946. preStr=pageMatch1[1];
  947. pageNum=parseInt(pageMatch1[2]);
  948. afterStr=pageMatch1[3];
  949. }else if(pageMatch2){
  950. preStr=pageMatch2[1];
  951. pageNum=parseInt(pageMatch2[2]);
  952. afterStr=pageMatch2[3];
  953. }
  954. let curPage=doc,i,cur,jsNext;
  955. let next1,next2,next3,next4,nextJs1,nextJs2,nextJs3;
  956. let next=curPage.querySelector(".page-next>a")||
  957. curPage.querySelector("a.next_page")||
  958. curPage.querySelector("#next_page")||
  959. curPage.querySelector(".nextPage")||
  960. curPage.querySelector("a[data-pagination=next]")||
  961. curPage.querySelector("ul.pagination>li.active+li>a")||
  962. curPage.querySelector(".pagination a[rel=next]")||
  963. curPage.querySelector(".pagination-nav__item--next>a")||
  964. curPage.querySelector("a[title='Next page']")||
  965. curPage.querySelector("a.pageright")||
  966. curPage.querySelector("a#rightFix")||
  967. curPage.querySelector("a#next")||
  968. curPage.querySelector(".next>a")||
  969. curPage.querySelector(".next>button")||
  970. curPage.querySelector("a[alt=next]")||
  971. curPage.querySelector("button.next")||
  972. curPage.querySelector("[title=next]")||
  973. curPage.querySelector("a#btnPreGn")||
  974. getElementByXpath("//a[contains(@class, 'page__next')]",curPage,curPage);
  975. if(!next){
  976. let nexts=curPage.querySelectorAll("a.next");
  977. for(i=0;i<nexts.length;i++){
  978. if(!/^([上前首尾][一1]?[页頁张張]|previous(\s*page)?\s*›?$|前のページ)/i.test(nexts[i].innerText.trim()) &&
  979. nexts[i].style.display!=="none" &&
  980. nexts[i].parentNode.style.display!=="none"){
  981. next=nexts[i];
  982. break;
  983. }
  984. }
  985. }
  986. if(next && (!next.href || /^javascript:/.test(next.href) || next.getAttribute("href")=="#")){
  987. jsNext=next;
  988. next=null;
  989. }
  990. if(!next){
  991. next=curPage.querySelectorAll("[aria-label='Next page']");
  992. if(next && next.length==1){
  993. next=next[0];
  994. if(!next.href || /^javascript:/.test(next.href) || next.getAttribute("href")=="#"){
  995. if(!jsNext)jsNext=next;
  996. next=null;
  997. }
  998. }else{
  999. next=null;
  1000. }
  1001. }
  1002. if(!next){
  1003. next=curPage.querySelectorAll("[aria-label='Next']");
  1004. if(next && next.length==1){
  1005. next=next[0];
  1006. if(!next.href || /^javascript:/.test(next.href) || next.getAttribute("href")=="#"){
  1007. if(!jsNext)jsNext=next;
  1008. next=null;
  1009. }
  1010. }else{
  1011. next=null;
  1012. }
  1013. }
  1014. if(next && /^[下后後][一1]?[章话話篇]/i.test(next.innerText.trim())){
  1015. next2=next;
  1016. next=null;
  1017. }
  1018. if(!next){
  1019. next=curPage.querySelector("a.curr");
  1020. if(next){
  1021. next=next.nextSibling;
  1022. }
  1023. }
  1024. if(!next){
  1025. next=curPage.querySelector("div.wp-pagenavi>span.current+a,div.page-nav>span.current+a,div.article-paging>span+a");
  1026. }
  1027. if(!next){
  1028. let pageDiv=curPage.querySelector("div.pages>ul");
  1029. if(pageDiv){
  1030. cur=pageDiv.querySelector("li>b");
  1031. if(cur)next=cur.parentNode.nextElementSibling;
  1032. if(next)next=next.querySelector("a");
  1033. }
  1034. }
  1035. if(!next){
  1036. cur=curPage.querySelector(".number>ul>li.active");
  1037. if(cur)next=cur.nextElementSibling;
  1038. if(next)next=next.querySelector("a");
  1039. }
  1040. if(!next){
  1041. let aTags=curPage.querySelectorAll("a,button");
  1042. for(i=aTags.length-1;i>=0;i--){
  1043. if(next1 && next2 && next3 && next4)break;
  1044. let aTag=aTags[i];
  1045. if(aTag.innerText=="§")continue;
  1046. if(aTag.innerText.length>50)continue;
  1047. if(aTag.style.display=="none")continue;
  1048. if(aTag.href && /next$/i.test(aTag.href))continue;
  1049. if(aTag.className && /slick|slide/i.test(aTag.className))continue;
  1050. if(aTag.innerText.length<=18){
  1051. if(!next1){
  1052. if(/^[下后後][一1]?[页頁张張]|^next([ _-]?page)?\s*[›>→»]?$|次のページ|^次へ?$/i.test(aTag.innerText.trim())){
  1053. if(!aTag.href || /^javascript:/.test(aTag.href) || aTag.getAttribute("href")=="#"){
  1054. if(!nextJs1)nextJs1=aTag;
  1055. }else{
  1056. next1=aTag;
  1057. }
  1058. }
  1059. }
  1060. if(!next2){
  1061. if(/^[下后後][一1]?[章话話篇]/i.test(aTag.innerText.trim()) || /nextpage/i.test(aTag.className)){
  1062. if(!aTag.href || /^javascript:/.test(aTag.href) || aTag.getAttribute("href")=="#"){
  1063. if(!nextJs2)nextJs2=aTag;
  1064. }else{
  1065. next2=aTag;
  1066. }
  1067. }
  1068. }
  1069. if(!next3){
  1070. if(aTag.innerText=="&gt;" || aTag.innerText=="▶" || aTag.innerText==">" || aTag.innerText=="›" || aTag.innerText=="→" || aTag.innerText=="»"){
  1071. if(!aTag.href || /^javascript:/.test(aTag.href) || aTag.getAttribute("href")=="#"){
  1072. if(!nextJs3)nextJs3=aTag;
  1073. }else{
  1074. next3=aTag;
  1075. }
  1076. }
  1077. }
  1078. }
  1079. if(!aTag.href || /^javascript:/.test(aTag.href) || aTag.getAttribute("href")=="#")continue;
  1080. if(!next4 && aTag.href.length<250){
  1081. let _aHref=aTag.href.replace("?&","?").replace("#!","").replace("index.php?","?");
  1082. let _aHrefTrim=_aHref;
  1083. if(preStr)_aHrefTrim=_aHrefTrim.replace(preStr,"");
  1084. if(afterStr)_aHrefTrim=_aHrefTrim.replace(afterStr,"");
  1085. if(pageNum<999 && _aHrefTrim==pageNum+1){
  1086. next4=aTag;
  1087. }else if(this.curUrl!=aTag.href){
  1088. _aHref=_aHref.replace(/\.s?html?$/i,"");
  1089. if(_aHref.indexOf(_url)!=-1 && /^[\/\?&]?[_-]?(p|page)?=?\/?2(\/|\?|&|$)/i.test(_aHref.replace(_url,""))){
  1090. let curHref=aTag.getAttribute("href");
  1091. let pageOne=curHref.replace(/\/2(\/|\?|&|$)/,"/1$1");
  1092. if(pageOne==curHref)pageOne=null;
  1093. else pageOne=curPage.querySelector(`a[href='${pageOne}']`);
  1094. if(!pageOne || pageOne.className!=curHref.className)next4=aTag;
  1095. }
  1096. }
  1097. }
  1098. }
  1099. if(next3){
  1100. let eles=getAllElementsByXpath(`//a[text()='${next3.innerText}']`,curPage,curPage);
  1101. if(eles.length>2)next3=null;
  1102. }
  1103. }
  1104. if(!next)next=next1||next4||next3||next2||jsNext||nextJs1||nextJs3||nextJs2;
  1105. if(next && next.classList.contains("results-more"))next=null;
  1106. return {next:next,canSave:canSave};
  1107. }
  1108.  
  1109. canonicalUri(src) {
  1110. if(src.charAt(0)=="#")return location.href+src;
  1111. var root_page = /^[^?#]*\//.exec(location.href)[0],
  1112. base_path = location.pathname.replace(/\/[^\/]+\.[^\/]+$/, "/"),
  1113. root_domain = /^\w+\:\/\/\/?[^\/]+/.exec(root_page)[0],
  1114. absolute_regex = /^\w+\:\/\//;
  1115. src=src.replace(/\.\//,"");
  1116. if (/^\/\/\/?/.test(src)){
  1117. src = location.protocol + src;
  1118. }
  1119. else if (!absolute_regex.test(src) && src.charAt(0) != "/"){
  1120. src = (base_path || "") + src;
  1121. }
  1122. return (absolute_regex.test(src) ? src : ((src.charAt(0) == "/" ? root_domain : root_page) + src));
  1123. }
  1124.  
  1125. getLinkByPage(url, pageNum) {
  1126. if(!url)return;
  1127. if(this.curSiteRule.pageNum){
  1128. let result=this.curSiteRule.pageNum;
  1129. let strMatch=result.match(/\{.*?}/);
  1130. if(!strMatch)return null;
  1131. let urlReg=new RegExp("("+result.replace(strMatch[0], ")\\d+(")+")","i");
  1132. let code=strMatch[0].replace(/^{/,"").replace(/}$/,"").replace(/\$p/g,pageNum);
  1133. if(code==pageNum){
  1134. result=url.replace(urlReg,"$1"+code+"$2");
  1135. }else{
  1136. try{
  1137. code=Function('"use strict";return ' + code)();
  1138. result=url.replace(urlReg,"$1"+code+"$2");
  1139. }catch(e){
  1140. debug(e);
  1141. }
  1142. }
  1143. if(result!=url){
  1144. return result;
  1145. }
  1146. }
  1147. return url.replace(/([&\/\?](p=|page[=\/_-]?))\d+/i, "$1"+pageNum).replace(/([_-])\d+\./i, "$1"+pageNum+".");
  1148. }
  1149.  
  1150. getPageNumFromUrl(url) {
  1151. if(!url)return curPage;
  1152. if(this.curSiteRule.pageNum){
  1153. let result=this.curSiteRule.pageNum;
  1154. let strMatch=result.match(/\{.*?}/);
  1155. if(!strMatch)return null;
  1156. let urlReg=new RegExp(".*"+result.replace(strMatch[0], "(\\d+)")+".*","i");
  1157. let curShowNum=url.replace(urlReg,"$1");
  1158. let code=strMatch[0].replace(/^{/,"").replace(/}$/,"");
  1159. if(code=="$p"){
  1160. return curShowNum;
  1161. }else{
  1162. try{
  1163. let page1=Function('"use strict";return ' + code.replace("$p", "0"))();
  1164. let page2=Function('"use strict";return ' + code.replace("$p", "1"))();
  1165. let numGap=page2-page1;
  1166. return (curShowNum - page1) / numGap;
  1167. }catch(e){
  1168. debug(e);
  1169. }
  1170. }
  1171. }else{
  1172. return url.replace(/.*[&\/\?](p=|page[=\/_-]?)(\d+).*/i, "$2").replace(/.*[_-](\d+)\..*/i, "$1");
  1173. }
  1174. return curPage;
  1175. }
  1176.  
  1177. getNextLink(doc) {
  1178. let nextLink=null,page,href;
  1179. let getNextLinkByForm=(form,n)=>{
  1180. let params=[];
  1181. [].forEach.call(form.querySelectorAll("input"), input=>{
  1182. if(n && /^(p|page)$/i.test(input.name)){
  1183. params.push('p='+n);
  1184. }else{
  1185. params.push(input.name+'='+input.value);
  1186. }
  1187. });
  1188. return form.action+'?'+params.join('&');
  1189. };
  1190. if(this.curSiteRule.pageElementByJs){
  1191. this.nextLinkHref="#";
  1192. return true;
  1193. }else if(this.curSiteRule.nextLinkByJs){
  1194. try{
  1195. let targetUrl=((typeof _unsafeWindow.pagetualNextLinkByJs=='undefined') ? Function("doc",'"use strict";' + this.curSiteRule.nextLinkByJs) : _unsafeWindow.pagetualNextLinkByJs)(doc);
  1196. if(targetUrl)nextLink={href:targetUrl};
  1197. }catch(e){
  1198. debug(e);
  1199. }
  1200. }else if(this.curSiteRule.nextLinkByUrl){
  1201. let targetUrl=this.curUrl.replace(new RegExp(this.curSiteRule.nextLinkByUrl[0],"i"), this.curSiteRule.nextLinkByUrl[1]);
  1202. if(targetUrl != this.curUrl){
  1203. let reps=targetUrl.match(/{.*?}/g);
  1204. if(reps){
  1205. reps.forEach(rep=>{
  1206. let code=rep.replace("{","").replace("}","");
  1207. let result=code.match(/^(\d*)\+1$/);
  1208. if(result){
  1209. result=parseInt(result[1]||1)+1;
  1210. }else{
  1211. try{
  1212. result=Function('"use strict";return ' + code)();
  1213. }catch(e){
  1214. debug(e);
  1215. }
  1216. }
  1217. targetUrl=targetUrl.replace(rep, result);
  1218. });
  1219. }
  1220. }
  1221. nextLink={href:targetUrl};
  1222. }else if(this.curSiteRule.nextLink){
  1223. if(this.curSiteRule.nextLink!="0" && this.curSiteRule.nextLink!=0){
  1224. nextLink=this.curSiteRule.type==0?getElementByXpath(this.curSiteRule.nextLink,doc,doc):doc.querySelector(this.curSiteRule.nextLink);
  1225. }
  1226. }else{
  1227. page=this.getPage(doc);
  1228. nextLink=page.next;
  1229. if(nextLink){
  1230. if(nextLink.tagName=="INPUT" && nextLink.parentNode.tagName=="FORM"){
  1231. let form=nextLink.parentNode;
  1232. nextLink.href=getNextLinkByForm(form);
  1233. }
  1234. if(nextLink.parentNode.style.display=="none" || nextLink.style.display=="none" || nextLink.classList.contains("noClick") || nextLink.hasAttribute("disabled")){
  1235. this.nextLinkHref=false;
  1236. return null;
  1237. }else if(doc==document){
  1238. if((!nextLink.href || /^javascript:/.test(nextLink.href)) && !isVisible(nextLink, _unsafeWindow)){
  1239. this.nextLinkHref=false;
  1240. return null;
  1241. }else{
  1242. let nextLinkCs=_unsafeWindow.getComputedStyle(nextLink);
  1243. if(nextLinkCs.cursor=="not-allowed"){
  1244. this.nextLinkHref=false;
  1245. return null;
  1246. }
  1247. this.initNext=nextLink;
  1248. }
  1249. }
  1250. let form=doc.querySelector('#search-form');
  1251. if(!nextLink.href && nextLink.hasAttribute("onclick") && form){
  1252. if(form && /^\d+$/.test(nextLink.innerText)){
  1253. href=getNextLinkByForm(form, nextLink.innerText);
  1254. }
  1255. }
  1256. }
  1257. }
  1258. if(nextLink){
  1259. let needUrl=(this.curSiteRule.action==0 || this.curSiteRule.action==1);
  1260. if(!href)href=nextLink.href;
  1261. if(href && nextLink.getAttribute){
  1262. let _href=nextLink.getAttribute("href");
  1263. if(!_href || _href.charAt(0)=="#" || _href=="?"){
  1264. href="#";
  1265. }
  1266. }
  1267.  
  1268. if((href===""||href===null) && needUrl){
  1269. this.nextLinkHref=false;
  1270. }else if(/^(javascript:void\(0\)|#)/.test(href) && needUrl){
  1271. this.nextLinkHref=false;
  1272. }else{
  1273. this.nextLinkHref=(href && !/^(javascript:|#)/.test(href))?this.canonicalUri(href):"#";
  1274. if(this.nextLinkHref!="#" && (this.nextLinkHref==this.curUrl || this.nextLinkHref==this.curUrl+"#" || this.nextLinkHref==this.oldUrl || this.nextLinkHref==this.oldUrl+"#")){
  1275. this.nextLinkHref=false;
  1276. }else if(doc==document)debug(nextLink);
  1277. }
  1278. }else{
  1279. this.nextLinkHref=false;
  1280. }
  1281. this.preload();
  1282. return nextLink;
  1283. }
  1284.  
  1285. preload(){
  1286. if(!rulesData.preload)return;
  1287. if(!this.nextLinkHref || this.nextLinkHref=="#")return;
  1288. let self=this;
  1289. if(this.curSiteRule && this.curSiteRule.action==1){
  1290. if(!this.preloadIframe){
  1291. this.preloadIframe = document.createElement('iframe');
  1292. let iframe = this.preloadIframe;
  1293. iframe.name = 'pagetual-iframe';
  1294. iframe.width = '100%';
  1295. iframe.height = '0';
  1296. iframe.frameBorder = '0';
  1297. if(ruleParser.curSiteRule.sandbox!=false){
  1298. iframe.sandbox="allow-same-origin allow-scripts allow-popups allow-forms";
  1299. }
  1300. iframe.style.cssText = 'margin:0!important;padding:0!important;visibility:hidden!important;';
  1301. iframe.addEventListener('load', function (e) {
  1302. try{
  1303. let doc=iframe.contentDocument || iframe.contentWindow.document;
  1304. var body = doc.body;
  1305. if (body && body.firstChild) {
  1306. self.lazyImgAction(body.children);
  1307. }
  1308. }catch(e){
  1309. return;
  1310. }
  1311. }, false);
  1312. document.body.appendChild(iframe);
  1313. }
  1314. this.preloadIframe.src = this.nextLinkHref;
  1315. }else{
  1316. _GM_xmlhttpRequest({
  1317. url: this.nextLinkHref,
  1318. method: 'GET',
  1319. overrideMimeType: 'text/html;charset='+document.charset,
  1320. headers: {
  1321. 'Referer': location.href
  1322. },
  1323. timeout: 5000,
  1324. onload: function(res) {
  1325. var doc=null;
  1326. try {
  1327. doc=document.implementation.createHTMLDocument('');
  1328. doc.documentElement.innerHTML=res.response;
  1329. var body = doc.body;
  1330. if (body && body.firstChild) {
  1331. self.lazyImgAction(body.children);
  1332. }
  1333. if(!self.preloadDiv){
  1334. self.preloadDiv = document.createElement('div');
  1335. self.preloadDiv.id = "pagetual-preload";
  1336. self.preloadDiv.style.cssText = 'display:none!important;';
  1337. document.body.appendChild(self.preloadDiv);
  1338. self.checkedImgs={};
  1339. }
  1340. [].forEach.call(doc.images, i=>{
  1341. let iSrc=i.src;
  1342. if(iSrc && !self.checkedImgs[iSrc]){
  1343. self.checkedImgs[iSrc] = true;
  1344. let img = document.createElement('img');
  1345. img.src = iSrc;
  1346. self.preloadDiv.appendChild(img);
  1347. }
  1348. });
  1349. }
  1350. catch (e) {
  1351. return;
  1352. }
  1353. }
  1354. });
  1355. }
  1356. }
  1357.  
  1358. getInsert(refresh) {
  1359. if(refresh){
  1360. this.insert=null;
  1361. }
  1362. if(this.insert && !refresh){
  1363. let parent=this.insert;
  1364. while(parent && parent.nodeName!="BODY"){
  1365. parent=parent.parentNode;
  1366. }
  1367. if(parent && parent.nodeName=="BODY"){
  1368. return this.insert;
  1369. }
  1370. }
  1371. if(this.curSiteRule.insert){
  1372. this.insert=this.curSiteRule.type==0?getElementByXpath(this.curSiteRule.insert,document):document.querySelector(this.curSiteRule.insert);
  1373. }else{
  1374. let pageElement=this.getPageElement(document, _unsafeWindow);
  1375. if(pageElement && pageElement.length>0){
  1376. var pELast = pageElement[pageElement.length - 1];
  1377. this.insert = pELast.nextSibling ? pELast.nextSibling : pELast.parentNode.appendChild(document.createTextNode(' '));
  1378. }
  1379. }
  1380. return this.insert;
  1381. }
  1382.  
  1383. pageInit(doc,eles){
  1384. let code=this.curSiteRule.pageInit;
  1385. if(code){
  1386. try{
  1387. ((typeof _unsafeWindow.pagetualPageInit=='undefined') ? Function("doc", "eles", '"use strict";' + code) : _unsafeWindow.pagetualPageInit)(doc, eles);
  1388. }catch(e){
  1389. debug(e);
  1390. }
  1391. }
  1392. }
  1393.  
  1394. pageAction(doc,eles){
  1395. let code=this.curSiteRule.pageAction;
  1396. if(code){
  1397. try{
  1398. ((typeof _unsafeWindow.pagetualPageAction=='undefined') ? Function("doc", "eles", '"use strict";' + code) : _unsafeWindow.pagetualPageAction)(doc, eles);
  1399. }catch(e){
  1400. debug(e);
  1401. }
  1402. }
  1403. this.lazyImgAction(eles);
  1404. this.openInNewTab(eles);
  1405. }
  1406.  
  1407. openInNewTab(eles){
  1408. if(rulesData.openInNewTab){
  1409. [].forEach.call(eles, ele=>{
  1410. if(ele.tagName=="A" && ele.href && !/^(mailto:|javascript:|#)/.test(ele.href)){
  1411. ele.setAttribute('target', '_blank');
  1412. }else{
  1413. [].forEach.call(ele.querySelectorAll('a[href]:not([href^="mailto:"]):not([href^="javascript:"]):not([href^="#"])'), a=>{
  1414. a.setAttribute('target', '_blank');
  1415. if (a.getAttribute('onclick') == 'atarget(this)') {
  1416. a.removeAttribute('onclick');
  1417. }
  1418. });
  1419. }
  1420. });
  1421. }
  1422. }
  1423.  
  1424. lazyImgAction(eles){
  1425. let setLazyImg=img=>{
  1426. let realSrc;
  1427. if(img.getAttribute("_src") && !img.src){
  1428. realSrc=img.getAttribute("_src");
  1429. }else if(img.dataset && img.dataset.original){
  1430. realSrc=img.dataset.original;
  1431. }else if(img.dataset && img.dataset.src){
  1432. realSrc=img.dataset.src;
  1433. }else if(img._lazyrias && img._lazyrias.srcset){
  1434. realSrc=img._lazyrias.srcset[img._lazyrias.srcset.length-1];
  1435. }else if(img.dataset && img.dataset.origFile){
  1436. realSrc=img.dataset.origFile;
  1437. }else if(img.srcset){
  1438. var srcs=img.srcset.split(/[xw],/),largeSize=0;
  1439. srcs.forEach(srci=>{
  1440. let srcInfo=srci.trim().split(" "),curSize=parseInt(srcInfo[1]);
  1441. if(srcInfo[1] && curSize>largeSize){
  1442. largeSize=curSize;
  1443. realSrc=srcInfo[0];
  1444. }
  1445. });
  1446. }
  1447. if(realSrc){
  1448. img.src=realSrc;
  1449. img.style.display="block";
  1450. }
  1451. };
  1452. [].forEach.call(eles, ele=>{
  1453. if(ele.tagName=="IMG"){
  1454. setLazyImg(ele);
  1455. }else{
  1456. [].forEach.call(ele.querySelectorAll("img"), img=>{
  1457. setLazyImg(img);
  1458. });
  1459. [].forEach.call(ele.querySelectorAll("div[data-src][data-thumb]"), div=>{
  1460. div.style.setProperty("background-image", "url("+div.dataset.src+")", "important");
  1461. });
  1462. }
  1463. if(ele.tagName=="A" && ele.classList.contains("lazyload")){
  1464. if(ele.dataset.original){
  1465. ele.style.backgroundImage='url("'+ele.dataset.original+'")';
  1466. }
  1467. }else{
  1468. [].forEach.call(ele.querySelectorAll("a.lazyload"), a=>{
  1469. if(a.dataset.original){
  1470. a.style.backgroundImage='url("'+a.dataset.original+'")';
  1471. }
  1472. });
  1473. }
  1474. });
  1475. let lazyImgSrc=this.curSiteRule.lazyImgSrc;
  1476. if(lazyImgSrc){
  1477. [].forEach.call(eles, ele=>{
  1478. [].forEach.call(ele.querySelectorAll("img"), img=>{
  1479. if(img.getAttribute(lazyImgSrc)){
  1480. img.src=img.getAttribute(lazyImgSrc);
  1481. }
  1482. });
  1483. });
  1484. }
  1485. }
  1486.  
  1487. initPage(callback){
  1488. let self=this;
  1489. curPage=1;
  1490. //if(this.curSiteRule.url && !this.curSiteRule.singleUrl)return;
  1491. this.curSiteRule={};
  1492. this.pageDoc=document;
  1493. this.nextLinkHref=null;
  1494. this.curUrl=location.href;
  1495. this.getRule(()=>{
  1496. if(self.curSiteRule.enable==0){
  1497. debug("Stop as rule disable");
  1498. isPause=true;
  1499. return;
  1500. }
  1501. //若是再亂匹配就不緩存wedata,或者只在找完本地規則之後再考慮wedata的緩存
  1502. if(self.curSiteRule && !self.curSiteRule.singleUrl && self.curSiteRule.url.length>13){
  1503. self.hpRules=self.hpRules.filter(item=>{return item&&item.url!=self.curSiteRule.url});
  1504. self.hpRules.unshift(self.curSiteRule);
  1505. if(self.hpRules.length>30){
  1506. self.hpRules.pop();
  1507. }
  1508. storage.setItem("hpRules", self.hpRules);
  1509. }
  1510. let css=self.curSiteRule.css;
  1511. if(css){
  1512. _GM_addStyle(css);
  1513. }
  1514. let autoClick=self.curSiteRule.autoClick;
  1515. if(autoClick){
  1516. let autoClickBtn;
  1517. try{
  1518. autoClickBtn=document.querySelector(autoClick);
  1519. }catch(e){
  1520. autoClickBtn=getElementByXpath(autoClick);
  1521. }
  1522. if(autoClickBtn){
  1523. emuClick(autoClickBtn);
  1524. }
  1525. }
  1526. let code=self.curSiteRule.init;
  1527. if(code){
  1528. try{
  1529. ((typeof _unsafeWindow.pagetualInit=='undefined') ? Function('doc','win','iframe','"use strict";' + code) : _unsafeWindow.pagetualInit)(null,null,null);
  1530. }catch(e){
  1531. debug(e);
  1532. }
  1533. }
  1534. self.getNextLink(document);
  1535. callback();
  1536. });
  1537. }
  1538.  
  1539. insertElement(ele) {
  1540. if(this.curSiteRule.insertPos==2){
  1541. this.insert.appendChild(ele);
  1542. }else{
  1543. this.insert.parentNode.insertBefore(ele, this.insert);
  1544. }
  1545. }
  1546.  
  1547. insertPage(doc, eles, url, callback, tried){
  1548. this.oldUrl=this.curUrl;
  1549. let oldTitle=this.pageDoc.title;
  1550. this.pageDoc=doc;
  1551. this.curUrl=url;
  1552. let nextLink=this.getNextLink(doc);
  1553. this.nextTitle="";
  1554. if(this.curSiteRule.pageBarText){
  1555. if(this.curSiteRule.pageBarText==1){
  1556. this.nextTitle=doc.title;
  1557. }else{
  1558. try{
  1559. this.nextTitle=((typeof _unsafeWindow.pagetualPageBarText=='undefined') ? Function("doc",'"use strict";' + this.curSiteRule.pageBarText) : _unsafeWindow.pagetualPageBarText)(doc);
  1560. }catch(e){
  1561. debug(e);
  1562. }
  1563. }
  1564. }
  1565. if(curPage==1 && !tried && !nextLink && this.curSiteRule.singleUrl && this.curSiteRule.pageElement && this.curSiteRule.action!=0){
  1566. this.curSiteRule.action=1;
  1567. this.curUrl=location.href;
  1568. return false;
  1569. }
  1570. if(callback)callback(eles);
  1571. this.getInsert();
  1572. var self=this,newEles=[];
  1573. if(!eles || eles.length==0 || !self.insert || !self.insert.parentNode){
  1574. }else{
  1575. this.pageInit(doc, eles);
  1576. [].forEach.call(eles, ele=>{
  1577. let newEle=ele.cloneNode(true);
  1578. let oldCanvass=ele.querySelectorAll("canvas");
  1579. let newCanvass=newEle.querySelectorAll("canvas");
  1580. for(let i=0;i<oldCanvass.length;i++){
  1581. let oldCanvas=oldCanvass[i];
  1582. let newCanvas=newCanvass[i];
  1583. newCanvas.getContext('2d').drawImage(oldCanvas, 0, 0);
  1584. }
  1585. self.insertElement(newEle);
  1586. newEles.push(newEle);
  1587. });
  1588. }
  1589. this.pageAction(doc, newEles);
  1590. if(this.oldUrl!=location.href){
  1591. let isJs=/^(javascript|#)/.test(this.oldUrl.replace(location.href,""));
  1592. let enableHistory = this.curSiteRule.history;
  1593. if (enableHistory == 1) {
  1594. enableHistory = true;
  1595. } else if (enableHistory == 0) {
  1596. enableHistory = false;
  1597. } else {
  1598. enableHistory = rulesData.enableHistory;
  1599. }
  1600. if(enableHistory && !isJs){
  1601. _unsafeWindow.history.replaceState(undefined, oldTitle, this.oldUrl);
  1602. document.title=oldTitle;
  1603. }
  1604. }
  1605. return true;
  1606. }
  1607. }
  1608. var ruleParser = new RuleParser();
  1609.  
  1610. function initConfig(){
  1611. initView();
  1612. _GM_registerMenuCommand(i18n(forceState==1?"enable":"disableSite"), ()=>{
  1613. forceState=(forceState==1?0:1);
  1614. storage.setItem("forceState_"+location.host, forceState);
  1615. showTips(i18n(forceState==1?"disableSiteTips":"enableSiteTips"));
  1616. if(!ruleParser.curSiteRule.url) location.reload();
  1617. });
  1618. _GM_registerMenuCommand(i18n("update"), ()=>{
  1619. updateRules(()=>{
  1620. showTips(i18n("updateSucc"));
  1621. location.reload();
  1622. },(rule,err)=>{
  1623. showTips("Update "+rule.url+" rules fail!");
  1624. });
  1625. showTips(i18n("beginUpdate"));
  1626. });
  1627.  
  1628. var configCon,insertPos;
  1629. if(ruleImportUrlReg.test(location.href)){
  1630. document.addEventListener("click", e=>{
  1631. if(e.target.tagName=="PRE"){
  1632. let nameAttr=e.target.getAttribute("name");
  1633. if(nameAttr=="pagetual" || nameAttr=="user-content-pagetual" || location.href.indexOf("greasyfork.org") != -1){
  1634. let rules=e.target.innerText.trim();
  1635. let isContent=/['"]name['"]/i.test(rules);
  1636. if(!window.confirm("Import?")) return;
  1637. if(isContent){
  1638. let ruleList=JSON.parse(`[${rules}]`);
  1639. for(let i in ruleList){
  1640. let hasRule = false;
  1641. let r = ruleList[i];
  1642. for(let j in ruleParser.customRules){
  1643. if(ruleParser.customRules[j].name == r.name){
  1644. ruleParser.customRules[j] = r;
  1645. hasRule = true;
  1646. break;
  1647. }
  1648. }
  1649. if(!hasRule)ruleParser.customRules.push(r);
  1650. }
  1651. storage.setItem("customRules", ruleParser.customRules);
  1652. showTips(i18n("importSucc"));
  1653. }else{
  1654. rules=rules.split("\n");
  1655. let diff=false;
  1656. for(let c=0;c<rules.length;c++){
  1657. let urlArr=rules[c].split("|"),url,type=1;
  1658. if(urlArr.length==1){
  1659. url=urlArr[0].trim();
  1660. if(!/^http/.test(url)){
  1661. showTips("Wrong url, check again!");
  1662. return;
  1663. }
  1664. }else if(urlArr.length==2){
  1665. type=urlArr[0].trim();
  1666. url=urlArr[1].trim();
  1667. if(!/^http/.test(url)){
  1668. showTips("Wrong url, check again!");
  1669. return;
  1670. }
  1671. }else{
  1672. break;
  1673. }
  1674. let maxId=0,hasUrl=false;
  1675. if(!rulesData.urls){
  1676. rulesData.urls=[];
  1677. maxId=1;
  1678. }else{
  1679. rulesData.urls.forEach(u=>{
  1680. if(maxId<u.id){
  1681. maxId=u.id;
  1682. }
  1683. if(u.url==url){
  1684. hasUrl=true;
  1685. }
  1686. });
  1687. if(hasUrl)break;
  1688. }
  1689. diff=true;
  1690. if(!rulesData.sort)rulesData.sort=[1];
  1691. rulesData.urls.push({id:maxId+1,url:url,type:type});
  1692. rulesData.sort.unshift(maxId+1);
  1693. }
  1694. if(!diff)return;
  1695. storage.setItem("rulesData", rulesData);
  1696.  
  1697. if(rulesData.urls)ruleUrls=ruleUrls.concat(rulesData.urls);
  1698. if(rulesData.sort){
  1699. let urls=[];
  1700. rulesData.sort.forEach(id=>{
  1701. for(let s=0;s<ruleUrls.length;s++){
  1702. if(id==ruleUrls[s].id){
  1703. urls.push(ruleUrls[s]);
  1704. break;
  1705. }
  1706. }
  1707. });
  1708. ruleUrls=urls;
  1709. }
  1710. updateRules(()=>{
  1711. showTips(i18n("updateSucc"));
  1712. location.reload();
  1713. },(rule,err)=>{
  1714. showTips("Update "+rule.url+" rules fail!");
  1715. });
  1716. showTips(i18n("beginUpdate"));
  1717. }
  1718. }
  1719. }
  1720. });
  1721. }
  1722. if(location.href==configPage){
  1723. _GM_addStyle(`
  1724. p>span:nth-child(1),p>span:nth-child(2),p>span:nth-child(3){
  1725. cursor: pointer;
  1726. user-select: none;
  1727. }
  1728. p>span:nth-child(1):hover,p>span:nth-child(2):hover,p>span:nth-child(3):hover{
  1729. color:red;
  1730. }
  1731. .updateDate{
  1732. cursor: pointer;
  1733. user-select: none;
  1734. }
  1735. .updateDate:hover{
  1736. color:red;
  1737. }
  1738. `);
  1739. document.querySelector("[name='user-content-click2import']").innerText=i18n("click2ImportRule")
  1740. configCon=document.querySelector(".markdown-body");
  1741. insertPos=configCon.querySelector("hr");
  1742.  
  1743. if(rulesData.urls && rulesData.urls.length>0){
  1744. document.querySelector("pre[name='user-content-pagetual']").style.display="none";
  1745. document.querySelector("p[name='user-content-click2import']").style.display="none";
  1746. }
  1747. }else return false;
  1748. class Rulebar {
  1749. init(ruleUrl){
  1750. this.ruleUrl=ruleUrl;
  1751. this.item=document.createElement("p");
  1752. this.item.title=ruleUrl.type==0?"AutoPagerize Rules":"Pagetual Rules";
  1753. this.item.dataset.id=this.ruleUrl.id;
  1754. let url=document.createElement("span");
  1755. url.innerHTML=ruleUrl.url;
  1756. let up=document.createElement("span");
  1757. up.innerHTML="↑ ";
  1758. up.title=i18n("sortTitle");
  1759. let down=document.createElement("span");
  1760. down.innerHTML="↓ ";
  1761. down.title=i18n("sortTitle");
  1762. let del=document.createElement("span");
  1763. del.innerHTML="× ";
  1764. up.onclick=e=>{
  1765. this.moveUp();
  1766. };
  1767. down.onclick=e=>{
  1768. this.moveDown();
  1769. };
  1770. del.onclick=e=>{
  1771. this.del();
  1772. };
  1773. this.item.appendChild(up);
  1774. this.item.appendChild(down);
  1775. this.item.appendChild(del);
  1776. this.item.appendChild(url);
  1777. configCon.insertBefore(this.item, insertPos);
  1778. }
  1779. saveSort(){
  1780. let sort=[];
  1781. [].forEach.call(this.item.parentNode.querySelectorAll("p[data-id]"), i=>{
  1782. sort.push(i.dataset.id);
  1783. });
  1784. rulesData.sort=sort;
  1785. storage.setItem("rulesData", rulesData);
  1786. }
  1787. moveUp(){
  1788. let preE=this.item.previousElementSibling;
  1789. if(preE.tagName=="P" && preE.children.length>1){
  1790. this.item.parentNode.insertBefore(this.item,preE);
  1791. this.saveSort();
  1792. }
  1793. }
  1794. moveDown(){
  1795. let nextE=this.item.nextElementSibling;
  1796. if(nextE.tagName=="P" && nextE.children.length>1){
  1797. this.item.parentNode.insertBefore(nextE,this.item);
  1798. this.saveSort();
  1799. }
  1800. }
  1801. del(){
  1802. if(this.ruleUrl.id<2){
  1803. showTips(i18n("cantDel"));
  1804. }else if(window.confirm(i18n("confirmDel"))){
  1805. for(let u=0;u<rulesData.urls.length;u++){
  1806. if(this.ruleUrl.id==rulesData.urls[u].id){
  1807. rulesData.urls.splice(u,1);
  1808. break;
  1809. }
  1810. }
  1811. for(let u=0;u<rulesData.sort.length;u++){
  1812. if(this.ruleUrl.id==rulesData.sort[u]){
  1813. rulesData.sort.splice(u,1);
  1814. break;
  1815. }
  1816. }
  1817. storage.setItem("rulesData", rulesData);
  1818. ruleParser.rules=ruleParser.rules.filter(item=>{return item.from!=this.ruleUrl.id});
  1819. storage.setItem("rules", ruleParser.rules);
  1820. this.item.parentNode.removeChild(this.item);
  1821. //location.reload();
  1822. }
  1823. }
  1824. }
  1825. let updateP=document.createElement("p"),i=0;
  1826. let now=new Date().getTime(),inUpdate=false;
  1827.  
  1828.  
  1829. let pastDate=(new Date(updateDate)).toString(),passStr;
  1830. let passTime=(now-updateDate)/1000;
  1831. if(isNaN(passTime)){
  1832. passStr=i18n("firstUpdate");
  1833. }else if(passTime<60){
  1834. passStr=i18n("passSec", parseInt(passTime))+" 👆 "+i18n("click2update");
  1835. }else if(passTime<60*60){
  1836. passStr=i18n("passMin", parseInt(passTime/60))+" 👆 "+i18n("click2update");
  1837. }else if(passTime<60*60*24){
  1838. passStr=i18n("passHour", parseInt(passTime/3600))+" 👆 "+i18n("click2update");
  1839. }else{
  1840. passStr=i18n("passDay", parseInt(passTime/86400))+" 👆 "+i18n("click2update");
  1841. }
  1842.  
  1843.  
  1844. updateP.className="updateDate";
  1845. updateP.innerHTML=passStr;
  1846. updateP.title=i18n("update")+" - "+pastDate;
  1847. updateP.onclick=e=>{
  1848. updateRules(()=>{
  1849. showTips(i18n("updateSucc"));
  1850. updateP.innerHTML=i18n("passSec", 0);
  1851. updateP.title=i18n("update");
  1852. },(rule,err)=>{
  1853. showTips("Update "+rule.url+" rules fail!");
  1854. });
  1855. showTips(i18n("beginUpdate"));
  1856. };
  1857. configCon.insertBefore(updateP, insertPos);
  1858. if(ruleUrls){
  1859. ruleUrls.forEach(ruleUrl=>{
  1860. var rulebar=new Rulebar();
  1861. rulebar.init(ruleUrl);
  1862. });
  1863. }
  1864. let customUrlsTitle=document.createElement("h2");
  1865. customUrlsTitle.innerHTML=i18n("customUrls");
  1866. configCon.insertBefore(customUrlsTitle, insertPos);
  1867. let customUrlsInput=document.createElement("textarea");
  1868. customUrlsInput.style.width="100%";
  1869. customUrlsInput.placeholder="0 | http://wedata.net/databases/AutoPagerize/items_all.json";
  1870. configCon.insertBefore(customUrlsInput, insertPos);
  1871.  
  1872. let upBtnImg=document.createElement("div");
  1873. upBtnImg.style.width="45%";
  1874. upBtnImg.style.float="left";
  1875. let upBtnImgTitle=document.createElement("h2");
  1876. upBtnImgTitle.style.whiteSpace="nowrap";
  1877. upBtnImgTitle.style.overflow="hidden";
  1878. upBtnImgTitle.innerHTML=i18n("upBtnImg");
  1879. upBtnImg.appendChild(upBtnImgTitle);
  1880. let upBtnImgInput=document.createElement("input");
  1881. upBtnImgInput.style.width="100%";
  1882. upBtnImgInput.placeholder="data:image/png;base64,UpBtn";
  1883. upBtnImgInput.value=rulesData.upBtnImg||'';
  1884. upBtnImg.appendChild(upBtnImgInput);
  1885. configCon.insertBefore(upBtnImg, insertPos);
  1886.  
  1887. let downBtnImg=document.createElement("div");
  1888. downBtnImg.style.width="45%";
  1889. downBtnImg.style.float="left";
  1890. let downBtnImgTitle=document.createElement("h2");
  1891. downBtnImgTitle.style.whiteSpace="nowrap";
  1892. downBtnImgTitle.style.overflow="hidden";
  1893. downBtnImgTitle.innerHTML=i18n("downBtnImg");
  1894. downBtnImg.appendChild(downBtnImgTitle);
  1895. let downBtnImgInput=document.createElement("input");
  1896. downBtnImgInput.style.width="100%";
  1897. downBtnImgInput.placeholder="data:image/png;base64,DownBtn";
  1898. downBtnImgInput.value=rulesData.downBtnImg||'';
  1899. downBtnImg.appendChild(downBtnImgInput);
  1900. configCon.insertBefore(downBtnImg, insertPos);
  1901.  
  1902. let opacity=document.createElement("div");
  1903. opacity.style.width="10%";
  1904. opacity.style.float="left";
  1905. opacity.style.marginBottom="50px";
  1906. let opacityTitle=document.createElement("h2");
  1907. opacityTitle.style.whiteSpace="nowrap";
  1908. opacityTitle.style.overflow="hidden";
  1909. opacityTitle.innerHTML=i18n("opacity");
  1910. opacity.appendChild(opacityTitle);
  1911. let opacityInput=document.createElement("input");
  1912. opacityInput.value=rulesData.opacity*100;
  1913. opacityInput.type="number";
  1914. opacityInput.style.width="95px";
  1915. opacityInput.style.margin="0";
  1916. opacity.appendChild(opacityInput);
  1917. configCon.insertBefore(opacity, insertPos);
  1918.  
  1919. let configTable=document.createElement("table");
  1920. configTable.style.width="100%";
  1921. let configTbody=document.createElement("tbody");
  1922. configTbody.style.width="100%";
  1923. configTbody.style.display="inline-table";
  1924. configTable.appendChild(configTbody);
  1925. configCon.insertBefore(configTable, insertPos);
  1926. function createCheckbox(innerText, val, tag, parentCheck, otherType){
  1927. if (typeof val == 'undefined') val = "";
  1928. let title=document.createElement(tag||"h3");
  1929. title.innerHTML=innerText;
  1930. let input=document.createElement("input");
  1931. input.type=otherType||"checkbox";
  1932. input.style.width="50px";
  1933. input.style.height="20px";
  1934. input.value=val;
  1935. input.checked=val;
  1936. let td=document.createElement("td");
  1937. td.appendChild(input);
  1938. if(parentCheck){
  1939. td.appendChild(title);
  1940. let parent=parentCheck.parentNode.nextElementSibling;
  1941. let tr=parent.querySelector("tr");
  1942. if(!tr){
  1943. tr=document.createElement("tr");
  1944. parent.appendChild(tr);
  1945. }
  1946. tr.appendChild(td);
  1947. if(!parentCheck.checked){
  1948. td.style.display="none";
  1949. }
  1950. parentCheck.addEventListener("click", e=>{
  1951. td.style.display=parentCheck.checked?"":"none";
  1952. });
  1953. }else{
  1954. let tr=document.createElement("tr");
  1955. tr.appendChild(td);
  1956. td=document.createElement("td");
  1957. td.appendChild(title);
  1958. tr.appendChild(td);
  1959. configTable.children[0].appendChild(tr);
  1960. }
  1961. return input;
  1962. }
  1963.  
  1964. let enableWhiteListInput=createCheckbox(i18n("autoRun"), rulesData.enableWhiteList!=true);
  1965. let enableDebugInput=createCheckbox(i18n("enableDebug"), rulesData.enableDebug!=false);
  1966. let enableHistoryInput=createCheckbox(i18n("enableHistory"), rulesData.enableHistory===true);
  1967. let openInNewTabInput=createCheckbox(i18n("openInNewTab"), rulesData.openInNewTab!=false);
  1968. let initRunInput=createCheckbox(i18n("initRun"), rulesData.initRun!=false);
  1969. let preloadInput=createCheckbox(i18n("preload"), rulesData.preload!=false);
  1970. let dbClick2StopInput=createCheckbox(i18n("dbClick2Stop"), rulesData.dbClick2Stop);
  1971. let hideBarInput=createCheckbox(i18n("hideBar"), rulesData.hideBar, "h4", dbClick2StopInput);
  1972. let dbClick2StopCtrlInput=createCheckbox(i18n("dbClick2StopCtrl"), rulesData.dbClick2StopCtrl, "h4", dbClick2StopInput);
  1973. let dbClick2StopAltInput=createCheckbox(i18n("dbClick2StopAlt"), rulesData.dbClick2StopAlt, "h4", dbClick2StopInput);
  1974. let dbClick2StopShiftInput=createCheckbox(i18n("dbClick2StopShift"), rulesData.dbClick2StopShift, "h4", dbClick2StopInput);
  1975. let dbClick2StopMetaInput=createCheckbox(i18n("dbClick2StopMeta"), rulesData.dbClick2StopMeta, "h4", dbClick2StopInput);
  1976. let dbClick2StopKeyInput=createCheckbox(i18n("dbClick2StopKey"), rulesData.dbClick2StopKey, "h4", dbClick2StopInput, "text");
  1977. dbClick2StopKeyInput.setAttribute("maxlength", "1");
  1978.  
  1979. let customRulesTitle=document.createElement("h2");
  1980. customRulesTitle.innerHTML=i18n("customRules");
  1981. configCon.insertBefore(customRulesTitle, insertPos);
  1982. let customRulesInput=document.createElement("textarea");
  1983. configCon.insertBefore(customRulesInput, insertPos);
  1984. if(rulesData.editTemp){
  1985. if(!ruleParser.customRules){
  1986. ruleParser.customRules=[];
  1987. }
  1988. for(let i in ruleParser.customRules){
  1989. if(ruleParser.customRules[i].url==rulesData.editTemp.url){
  1990. ruleParser.customRules.splice(i, 1);
  1991. break;
  1992. }
  1993. }
  1994. ruleParser.customRules.unshift(rulesData.editTemp);
  1995. rulesData.editTemp=null;
  1996. storage.setItem("rulesData", rulesData);
  1997. customRulesInput.previousElementSibling.scrollIntoView();
  1998. }
  1999. customRulesInput.style.width="100%";
  2000. customRulesInput.style.height="800px";
  2001. 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]`;
  2002. customRulesInput.value=getFormatJSON(ruleParser.customRules);
  2003. let blacklistInput=document.createElement("textarea");
  2004. blacklistInput.style.width="100%";
  2005. blacklistInput.style.height="500px";
  2006. blacklistInput.style.display="none";
  2007. blacklistInput.placeholder="http://*.xxx.com/*/y";
  2008. blacklistInput.value=rulesData.blacklist?rulesData.blacklist.join("\n"):"";
  2009. let blacklistBtn=document.createElement("button");
  2010. blacklistBtn.innerText=i18n("editBlacklist");
  2011. blacklistBtn.style.width="100%";
  2012. blacklistBtn.onclick=e=>{
  2013. blacklistInput.style.display=blacklistInput.style.display=="none"?"":"none";
  2014. };
  2015. configCon.insertBefore(blacklistBtn, insertPos);
  2016. configCon.insertBefore(blacklistInput, insertPos);
  2017. let saveBtn=document.createElement("button");
  2018. saveBtn.innerHTML=i18n("save");
  2019. saveBtn.style.width="100%";
  2020. configCon.insertBefore(saveBtn, insertPos);
  2021. saveBtn.onclick=e=>{
  2022. try{
  2023. storage.setItem("hpRules", []);
  2024. if(customRulesInput.value==""){
  2025. storage.setItem("customRules", "");
  2026. }else{
  2027. let customRules=JSON.parse(customRulesInput.value);
  2028. if(Array && Array.isArray && !Array.isArray(customRules)){
  2029. showTips("Rules must be a Array!");
  2030. return;
  2031. }
  2032. debug(customRules);
  2033. storage.setItem("customRules", customRules);
  2034. }
  2035. }catch(e){
  2036. debug(e);
  2037. showTips("JSON error, check again!");
  2038. return;
  2039. }
  2040. rulesData.opacity=opacityInput.value/100;
  2041. rulesData.blacklist=blacklistInput.value?blacklistInput.value.split("\n"):"";
  2042. rulesData.hideBar=hideBarInput.checked;
  2043. rulesData.dbClick2Stop=dbClick2StopInput.checked;
  2044. rulesData.enableWhiteList=!enableWhiteListInput.checked;
  2045. rulesData.enableDebug=enableDebugInput.checked;
  2046. rulesData.enableHistory=enableHistoryInput.checked;
  2047. rulesData.openInNewTab=openInNewTabInput.checked;
  2048. rulesData.initRun=initRunInput.checked;
  2049. rulesData.preload=preloadInput.checked;
  2050. rulesData.upBtnImg=upBtnImgInput.value;
  2051. rulesData.downBtnImg=downBtnImgInput.value;
  2052. rulesData.dbClick2StopCtrl=dbClick2StopCtrlInput.checked;
  2053. rulesData.dbClick2StopAlt=dbClick2StopAltInput.checked;
  2054. rulesData.dbClick2StopShift=dbClick2StopShiftInput.checked;
  2055. rulesData.dbClick2StopMeta=dbClick2StopMetaInput.checked;
  2056. rulesData.dbClick2StopKey=dbClick2StopKeyInput.value;
  2057. storage.setItem("rulesData", rulesData);
  2058. let customUrls=customUrlsInput.value.trim();
  2059. if(customUrls){
  2060. customUrls=customUrls.split(/\n/);
  2061. for(let c=0;c<customUrls.length;c++){
  2062. let urlArr=customUrls[c].split("|"),url,type=1;
  2063. if(urlArr.length==1){
  2064. url=urlArr[0].trim();
  2065. if(!/^http/.test(url)){
  2066. showTips("Wrong url, check again!");
  2067. return;
  2068. }
  2069. }else if(urlArr.length==2){
  2070. type=urlArr[0].trim();
  2071. url=urlArr[1].trim();
  2072. if(!/^http/.test(url)){
  2073. showTips("Wrong url, check again!");
  2074. return;
  2075. }
  2076. }else{
  2077. break;
  2078. }
  2079. let maxId=0,hasUrl=false;
  2080. if(!rulesData.urls){
  2081. rulesData.urls=[];
  2082. maxId=1;
  2083. }else{
  2084. rulesData.urls.forEach(u=>{
  2085. if(maxId<u.id){
  2086. maxId=u.id;
  2087. }
  2088. if(u.url==url){
  2089. hasUrl=true;
  2090. }
  2091. });
  2092. if(hasUrl)break;
  2093. }
  2094. if(!rulesData.sort)rulesData.sort=[1];
  2095. rulesData.urls.push({id:maxId+1,url:url,type:type});
  2096. rulesData.sort.push(maxId+1);
  2097. storage.setItem("rulesData", rulesData);
  2098. }
  2099. }
  2100. showTips("The settings are saved");
  2101. location.reload();
  2102. };
  2103. return true;
  2104. }
  2105.  
  2106. var inUpdate=false;
  2107. function updateRules(success,fail){
  2108. if(inUpdate)return;
  2109. inUpdate=true;
  2110. let ruleIndex=ruleUrls.length-1;
  2111. storage.setItem("hpRules", []);
  2112. function addNextRule(){
  2113. if(ruleIndex<0){
  2114. let now=new Date().getTime();
  2115. storage.setItem("ruleLastUpdate", now);
  2116. storage.setItem("rules", ruleParser.rules);
  2117. inUpdate=false;
  2118. success();
  2119. }else{
  2120. let rule=ruleUrls[ruleIndex--];
  2121. ruleParser.addRuleByUrl(rule.url, rule.type, rule.id, (json,err)=>{
  2122. if(!json){
  2123. fail(rule,err);
  2124. }
  2125. addNextRule();
  2126. })
  2127. }
  2128. }
  2129. addNextRule();
  2130. }
  2131.  
  2132. function objIsArr(obj) {
  2133. return obj &&
  2134. typeof obj === 'object' &&
  2135. typeof obj.length === 'number' &&
  2136. !(obj.propertyIsEnumerable('length'));
  2137. }
  2138.  
  2139. function isVisible(el, win) {
  2140. if(!el.offsetParent)return false;
  2141. var loopable = true,
  2142. visible = el.tagName && win.getComputedStyle(el).display != 'none' && win.getComputedStyle(el).visibility != 'hidden';
  2143. while(loopable && visible) {
  2144. el = el.parentNode;
  2145.  
  2146. if(el && el.tagName && el.tagName!="BODY") {
  2147. visible = win.getComputedStyle(el).display != 'none' && win.getComputedStyle(el).visibility != 'hidden';
  2148. }else {
  2149. loopable = false;
  2150. }
  2151. }
  2152. return visible;
  2153. }
  2154.  
  2155. function getElementTop(ele) {
  2156. var actualTop = ele.offsetTop;
  2157. var current = ele.offsetParent;
  2158. while (current) {
  2159. actualTop += current.offsetTop;
  2160. current = current.offsetParent;
  2161. }
  2162. return actualTop;
  2163. }
  2164.  
  2165. function getFormatJSON(obj){
  2166. if(!objIsArr(obj) || obj.length === 0)return "";
  2167. return JSON.stringify(obj, null, 4);
  2168. let ret="[\n";
  2169. let len=obj.length,i=0,isLast;
  2170. obj.forEach(item=>{
  2171. ret+=" {\n";
  2172. let iLen=Object.keys(item).length,j=0;
  2173. for(let key in item){
  2174. isLast=(++j)==iLen;
  2175. let value=item[key];
  2176. if(objIsArr(value)){
  2177. let vstr="[",v=0,vIsLast=false;
  2178. value.forEach(vi=>{
  2179. vIsLast=(++v)==value.length;
  2180. vstr+="\""+vi.replace(/\\/g,"\\\\")+"\""+(vIsLast?"":",");
  2181. });
  2182. vstr+="]";
  2183. ret+=" \""+key+"\":"+vstr+""+(isLast?"":",")+"\n";
  2184. }else{
  2185. if(typeof value=="string"){
  2186. value=value.replace(/\\/g,"\\\\").replace(/"/g,"\\\"");
  2187. value="\""+value+"\"";
  2188. }
  2189. ret+=" \""+key+"\":"+value+""+(isLast?"":",")+"\n";
  2190. }
  2191. }
  2192. isLast=(++i)==len;
  2193. ret+=" }"+(isLast?"":",")+"\n";
  2194. });
  2195. ret+="]";
  2196. return ret;
  2197. }
  2198.  
  2199. function globMatch(first, second) {
  2200. if (first.length == 0 && second.length == 0){
  2201. return true;
  2202. }
  2203.  
  2204. if (first.length > 1 && first[0] == '*' &&
  2205. second.length == 0){
  2206. return false;
  2207. }
  2208.  
  2209. if ((first.length > 1 && first[0] == '?') ||
  2210. (first.length != 0 && second.length != 0 &&
  2211. first[0] == second[0])){
  2212. return globMatch(first.substring(1),
  2213. second.substring(1));
  2214. }
  2215.  
  2216. if (first.length > 0 && first[0] == '*'){
  2217. return globMatch(first.substring(1), second) ||
  2218. globMatch(first, second.substring(1));
  2219. }
  2220.  
  2221. return false;
  2222. }
  2223.  
  2224. function initRules(callback) {
  2225. /*0 wedata格式,1 pagetual格式*/
  2226. ruleUrls=[
  2227. {
  2228. id:1,
  2229. url:'http://wedata.net/databases/AutoPagerize/items_all.json',
  2230. type:0,
  2231. }
  2232. ];var i=0,j=0;
  2233.  
  2234. ruleParser.initSavedRules(()=>{
  2235. storage.getItem("rulesData", data=>{
  2236. if(data){
  2237. rulesData=data;
  2238. if(data.urls)ruleUrls=ruleUrls.concat(data.urls);
  2239. if(data.sort){
  2240. let urls=[];
  2241. data.sort.forEach(id=>{
  2242. for(let s=0;s<ruleUrls.length;s++){
  2243. if(id==ruleUrls[s].id){
  2244. urls.push(ruleUrls[s]);
  2245. break;
  2246. }
  2247. }
  2248. });
  2249. ruleUrls=urls;
  2250. }
  2251. }
  2252. let upBtnImg=rulesData.upBtnImg,downBtnImg=rulesData.downBtnImg;
  2253. if(upBtnImg && downBtnImg){
  2254. downSvgCSS=downSvgCSS.replace("transform: rotate(180deg);","");
  2255. }else if(upBtnImg && !downBtnImg){
  2256. downBtnImg=upBtnImg;
  2257. }else if(downBtnImg && !upBtnImg){
  2258. upBtnImg=downBtnImg;
  2259. }
  2260. if(upBtnImg){
  2261. upSvg=`<img src="${upBtnImg}"/>`;
  2262. }
  2263. if(downBtnImg){
  2264. downSvg=`<img src="${downBtnImg}"/>`;
  2265. }
  2266. if(typeof(rulesData.opacity)=="undefined"){
  2267. rulesData.opacity=0.3;
  2268. }
  2269. if(typeof(rulesData.hideBar)=="undefined"){
  2270. rulesData.hideBar=false;
  2271. }
  2272. if(typeof(rulesData.dbClick2Stop)=="undefined"){
  2273. rulesData.dbClick2Stop=true;
  2274. }
  2275. if(typeof(rulesData.enableWhiteList)=="undefined"){
  2276. rulesData.enableWhiteList=false;
  2277. }
  2278. if(typeof(rulesData.enableHistory)=="undefined"){
  2279. rulesData.enableHistory=false;
  2280. }
  2281. if(typeof(rulesData.openInNewTab)=="undefined"){
  2282. rulesData.openInNewTab=true;
  2283. }
  2284. if(typeof(rulesData.enableDebug)=="undefined"){
  2285. rulesData.enableDebug=true;
  2286. }
  2287. if(typeof(rulesData.initRun)=="undefined"){
  2288. rulesData.initRun=true;
  2289. }
  2290. if(typeof(rulesData.preload)=="undefined"){
  2291. rulesData.preload=true;
  2292. }
  2293. if(rulesData.blacklist && rulesData.blacklist.length>0){
  2294. for(let b in rulesData.blacklist){
  2295. let curGlob=rulesData.blacklist[b];
  2296. if(globMatch(curGlob, location.href)){
  2297. return;
  2298. }
  2299. }
  2300. }
  2301. enableDebug=rulesData.enableDebug;
  2302. storage.getItem("forceState_"+location.host, v=>{
  2303. storage.getItem("ruleLastUpdate", date=>{
  2304. if(typeof(v)=="undefined"){
  2305. v=(rulesData.enableWhiteList?1:0);
  2306. }
  2307. forceState=v;
  2308. updateDate=date;
  2309. if(initConfig())return;
  2310. if(forceState==1)return;
  2311. let now=new Date().getTime();
  2312. if(!date || now-date>2*24*60*60*1000){
  2313. updateRules(()=>{
  2314. },(rule,err)=>{});
  2315. storage.setItem("ruleLastUpdate", now);
  2316. }
  2317. callback();
  2318. });
  2319. });
  2320. });
  2321. });
  2322. }
  2323.  
  2324. function requestDoc(url, callback){
  2325. _GM_xmlhttpRequest({
  2326. url: url,
  2327. method: 'GET',
  2328. overrideMimeType: 'text/html;charset='+document.charset,
  2329. headers: {
  2330. 'Referer': location.href,
  2331. "Content-Type": "text/html;charset="+document.charset,
  2332. },
  2333. timeout: 5000,
  2334. onload: function(res) {
  2335. var doc=null,response=res.response;
  2336. let preCode=ruleParser.curSiteRule.pageElementPre || ruleParser.curSiteRule.pagePre;
  2337. if(preCode){
  2338. try{
  2339. if (typeof _unsafeWindow.pagetualPagePre!='undefined') {
  2340. response = _unsafeWindow.pagetualPagePre(response);
  2341. } else if (preCode.length == 2) {
  2342. response = response.replace(new RegExp(preCode[0], "gi"), preCode[1]);
  2343. } else {
  2344. response = Function("response",'"use strict";' + preCode)(response);
  2345. }
  2346. }catch(e){
  2347. debug(e);
  2348. }
  2349. }
  2350. try {
  2351. doc=document.implementation.createHTMLDocument('');
  2352. doc.documentElement.innerHTML=response;
  2353. }
  2354. catch (e) {
  2355. debug('parse error'+e.toString());
  2356. }
  2357. let pageElement=ruleParser.getPageElement(doc);
  2358. if(inCors && (!pageElement || pageElement.length==0)){
  2359. ruleParser.curSiteRule.pageElement=allOfBody;
  2360. pageElement=ruleParser.getPageElement(doc);
  2361. ruleParser.getInsert(true);
  2362. }
  2363. //只有1的話怕不是圖片哦
  2364. if(pageElement && (pageElement.length>1 || (pageElement.length==1 && pageElement[0].tagName!="IMG") )){
  2365. let result=ruleParser.insertPage(doc, pageElement, url, callback, false);
  2366. ruleParser.curSiteRule.action=0;
  2367. if(!result){
  2368. ruleParser.curSiteRule.action=1;
  2369. requestFromIframe(url, (doc, eles)=>{
  2370. loadPageOver();
  2371. if(eles){
  2372. ruleParser.insertPage(doc, eles, url, callback, true);
  2373. }
  2374. });
  2375. }
  2376. }else if(ruleParser.curSiteRule.singleUrl || curPage==1){
  2377. ruleParser.curSiteRule.action=1;
  2378. requestFromIframe(url, (doc, eles)=>{
  2379. loadPageOver();
  2380. if(eles){
  2381. ruleParser.insertPage(doc, eles, url, callback, true);
  2382. }
  2383. });
  2384. }else{
  2385. isPause=true;
  2386. callback(false);
  2387. }
  2388. },
  2389. onerror: function(e){
  2390. debug(e);
  2391. callback(false);
  2392. },
  2393. ontimeout: function(e){
  2394. debug(e);
  2395. callback(false);
  2396. }
  2397. });
  2398. }
  2399.  
  2400. function initPage(){
  2401. ruleParser.initPage(()=>{
  2402. if(ruleParser.nextLinkHref){
  2403. let isJs=/^(javascript|#)/.test(ruleParser.nextLinkHref.replace(location.href,""));
  2404. if(!isJs){
  2405. let inForce=(forceState == 2 || forceState == 3);
  2406. _GM_registerMenuCommand(i18n(inForce?"cancelForceIframe":"forceIframe"), ()=>{
  2407. if(inForce){
  2408. storage.setItem("forceState_"+location.host, "");
  2409. }else{
  2410. let _state=ruleParser.curSiteRule.action>0 || confirm(i18n("forceAllBody"))?2:3;
  2411. storage.setItem("forceState_"+location.host, _state);
  2412. }
  2413. location.reload();
  2414. });
  2415. }
  2416. _GM_registerMenuCommand(i18n("loadNow"), ()=>{
  2417. let loadNum=window.prompt(i18n("loadConfirm"), "1");
  2418. if(loadNum==="" || loadNum===null)return;
  2419. autoLoadNum=Math.abs(parseInt(loadNum));
  2420. nextPage();
  2421. });
  2422. }
  2423. initListener();
  2424. if(rulesData.initRun && ruleParser.curSiteRule.initRun!=0)nextPage();
  2425. });
  2426. }
  2427.  
  2428. var pageBarStyle;
  2429. function initView(){
  2430. _GM_addStyle(`
  2431. .pagetual_pageBar{
  2432. -moz-transition:opacity 0.3s ease-in-out 0s;
  2433. -webkit-transition:opacity 0.3s ease-in-out 0s;
  2434. transition:opacity 0.3s ease-in-out 0s;
  2435. }
  2436. .pagetual_pageBar.stop {
  2437. -webkit-filter: invert(100%);
  2438. filter: invert(100%);
  2439. opacity: 1!important;
  2440. }
  2441. .pagetual_pageBar.hide {
  2442. display: none!important;
  2443. }
  2444. .pagetual_pageBar:hover {
  2445. opacity: 1!important;
  2446. }
  2447. .pagetual_pageBar span {
  2448. vertical-align: super;
  2449. }
  2450. .pagetual_pageBar a>span {
  2451. margin-top: 0!important;
  2452. opacity: 0;
  2453. -moz-transition:all 0.3s ease-in-out 0s;
  2454. -webkit-transition:all 0.3s ease-in-out 0s;
  2455. transition:all 0.3s ease-in-out 0s;
  2456. }
  2457. .pagetual_pageBar a>span:hover {
  2458. color: red;
  2459. }
  2460. .pagetual_pageBar a:hover>span {
  2461. opacity: 1;
  2462. }
  2463. .pagetual_pageBar a:hover>span.prev {
  2464. margin-top: -30px!important;
  2465. }
  2466. .pagetual_pageBar a:hover>span.next {
  2467. margin-top: 30px!important;
  2468. }
  2469.  
  2470. .pagetual_pageBar span>svg:hover {
  2471. animation: touhouAni 1s infinite;
  2472. }
  2473. .pagetual_pageBar .pagetual_pageNum{
  2474. color: #55555f;
  2475. }
  2476. .pagetual_pageBar .pagetual_pageNum:hover{
  2477. color: #ff6464;
  2478. }
  2479. .pagetual_tipsWords{
  2480. font-size: 50px;
  2481. font-weight: bold;
  2482. font-family: "黑体", -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto",
  2483. "Oxygen", "Ubuntu", "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji",
  2484. "Segoe UI Emoji", "Segoe UI Symbol";
  2485. color: #ffffff;
  2486. height: 70px;
  2487. line-height: 70px;
  2488. position: fixed;
  2489. left: 50%;
  2490. top: 10%;
  2491. margin-left: -150px;
  2492. padding: 0 10px;
  2493. z-index: 999999999;
  2494. background-color: #000;
  2495. border: 1px solid black;
  2496. border-radius: 10px;
  2497. opacity: 0;
  2498. filter: alpha(opacity=65);
  2499. box-shadow: 5px 5px 20px 0px #000;
  2500. -moz-transition:opacity 0.3s ease-in-out 0s;
  2501. -webkit-transition:opacity 0.3s ease-in-out 0s;
  2502. transition:opacity 0.3s ease-in-out 0s;
  2503. pointer-events: none;
  2504. }
  2505.  
  2506. @keyframes touhouAni{
  2507. from {transform: rotate(0deg) scale3d(1.2, 1.2, 1.2);}
  2508. to {transform: rotate(360deg);}
  2509. }
  2510. @-webkit-keyframes touhouAni{
  2511. from {transform: rotate(0deg) scale3d(1.2, 1.2, 1.2);}
  2512. to {transform: rotate(360deg);}
  2513. }
  2514. .pagetual_loading {
  2515. width: 50px;
  2516. height: 50px;
  2517. margin: 10px auto;
  2518. border-radius: 100%;
  2519. -webkit-animation: pagetual_loading_scaleout 1.0s infinite ease-in-out;
  2520. animation: pagetual_loading_scaleout 1.0s infinite ease-in-out;
  2521. }
  2522. @-webkit-keyframes pagetual_loading_scaleout {
  2523. 0% { -webkit-transform: scale(0.0) }
  2524. 100% {
  2525. -webkit-transform: scale(1.0);
  2526. opacity: 0;
  2527. }
  2528. }
  2529. @keyframes pagetual_loading_scaleout {
  2530. 0% {
  2531. transform: scale(0.0);
  2532. -webkit-transform: scale(0.0);
  2533. } 100% {
  2534. transform: scale(1.0);
  2535. -webkit-transform: scale(1.0);
  2536. opacity: 0;
  2537. }
  2538. }
  2539. .pagetual_loading_text {
  2540. -webkit-animation: pagetual_loading_opacity 2.6s infinite ease-in-out;
  2541. animation: pagetual_loading_opacity 2.6s infinite ease-in-out;
  2542. }
  2543. @-webkit-keyframes pagetual_loading_opacity {
  2544. 0% { opacity: 1 }
  2545. 50% { opacity: 0.2 }
  2546. 100% { opacity: 1 }
  2547. }
  2548. @keyframes pagetual_loading_opacity {
  2549. 0% { opacity: 1 }
  2550. 50% { opacity: 0.2 }
  2551. 100% { opacity: 1 }
  2552. }
  2553. `);
  2554. 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;`;
  2555. }
  2556. var loadingDiv=document.createElement("div");
  2557. 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;";
  2558. loadingDiv.innerHTML=`<p class="pagetual_loading_text" style="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;">${i18n("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>`;
  2559. var 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;`;
  2560.  
  2561. var upSvg=`<svg width="30" height="30" 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>`;
  2562. var upSvgCSS=`display:initial;position:absolute;cursor: pointer;margin: 0 -45px;width: 30px;height: 30px;vertical-align: middle;fill: currentColor;overflow: hidden;`;
  2563. var downSvg=`<svg width="30" height="30" 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>`;
  2564. 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);`;
  2565.  
  2566. var 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;`;
  2567. var pageTextStyle=`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;`;
  2568.  
  2569. var tipsWords=document.createElement("div");
  2570. tipsWords.className="pagetual_tipsWords";
  2571.  
  2572. var isPause=false,isLoading=false,curPage=1,forceState=0,bottomGap=1000,autoLoadNum=-1;
  2573.  
  2574. function changeStop(stop, hide){
  2575. isPause=stop;
  2576. [].forEach.call(document.querySelectorAll(".pagetual_pageBar"), bar=>{
  2577. if(isPause){
  2578. bar.classList.add("stop");
  2579. if(hide)bar.classList.add("hide");
  2580. }else{
  2581. bar.classList.remove("stop");
  2582. if(hide)bar.classList.remove("hide");
  2583. }
  2584. });
  2585. }
  2586.  
  2587. function isInViewPort(element) {
  2588. if(!element.parentNode)return false;
  2589. if(_unsafeWindow.getComputedStyle(element).display=="none")return false;
  2590. const viewWidth = window.innerWidth || document.documentElement.clientWidth;
  2591. const viewHeight = window.innerHeight || document.documentElement.clientHeight;
  2592. const {
  2593. top,
  2594. right,
  2595. bottom,
  2596. left,
  2597. } = element.getBoundingClientRect();
  2598.  
  2599. return (
  2600. top >= 0 &&
  2601. left >= 0 &&
  2602. right <= viewWidth + 1 &&
  2603. bottom <= viewHeight * 2
  2604. );
  2605. }
  2606.  
  2607. var urlChanged=false;
  2608. var _wr = function(type) {
  2609. var orig = history[type];
  2610. return function() {
  2611. var rv = orig.apply(this, arguments);
  2612. var e = new Event(type);
  2613. e.arguments = arguments;
  2614. window.dispatchEvent(e);
  2615. return rv;
  2616. };
  2617. };
  2618. history.pushState = _wr('pushState');
  2619. window.addEventListener('pushState', function(e) {
  2620. urlChanged=true;
  2621. isPause=true;
  2622. setTimeout(()=>{
  2623. if(location.href==configPage){
  2624. location.reload();
  2625. }
  2626. },1);
  2627. });
  2628.  
  2629. function initListener(){
  2630. let loadmoreBtn,loading=true,lastScroll=0,checkLoadMoreTimes=0;
  2631. let checkLoadMore=setInterval(()=>{
  2632. loadmoreBtn=getLoadMore(document);
  2633. if(loadmoreBtn && isVisible(loadmoreBtn, _unsafeWindow)){
  2634. loading=false;
  2635. clearInterval(checkLoadMore);
  2636. }else if(checkLoadMoreTimes>10){
  2637. clearInterval(checkLoadMore);
  2638. }
  2639. },300);
  2640. let checkScrollReach=()=>{
  2641. let scrolly=window.scrollY;
  2642. let windowHeight=window.innerHeight || document.documentElement.clientHeight;
  2643. let scrollH=Math.max(document.documentElement.scrollHeight, document.body.scrollHeight);
  2644. if(scrollH-scrolly-windowHeight<bottomGap){
  2645. nextPage();
  2646. }
  2647. };
  2648. let scrollHandler = e=>{
  2649. if(urlChanged){
  2650. ruleParser.initPage(()=>{
  2651. if(ruleParser.nextLinkHref)initView();
  2652. });
  2653. urlChanged=false;
  2654. isPause=false;
  2655. }
  2656. if(isPause)return;
  2657. if(!loading){
  2658. if(!loadmoreBtn || !loadmoreBtn.parentNode){
  2659. loadmoreBtn=getLoadMore(document);
  2660. }
  2661. if(loadmoreBtn){
  2662. if(isInViewPort(loadmoreBtn)){
  2663. emuClick(loadmoreBtn);
  2664. loading=true;
  2665. setTimeout(()=>{loading=false},200);
  2666. }
  2667. }else{
  2668. loading=true;
  2669. setTimeout(()=>{loading=false},200);
  2670. }
  2671. }
  2672. if(!isLoading){
  2673. checkScrollReach();
  2674. }
  2675. if(ruleParser.curSiteRule.lockScroll){
  2676. let curScroll=document.body.scrollTop||document.documentElement.scrollTop;
  2677. if(lastScroll!=0 && isLoading && Math.abs(lastScroll-curScroll)>100){
  2678. document.body.scrollTop=lastScroll;
  2679. document.documentElement.scrollTop=lastScroll;
  2680. }else{
  2681. lastScroll=curScroll;
  2682. }
  2683. }
  2684. };
  2685. if(!ruleParser.curSiteRule.wheel){
  2686. document.addEventListener('scroll', scrollHandler, true);
  2687. }
  2688. document.addEventListener('wheel', scrollHandler, true);
  2689. document.addEventListener('dblclick', e=>{
  2690. if(forceState==1 || e.target.tagName=='INPUT' || e.target.tagName=='TEXTAREA') return;
  2691. if(!rulesData.dbClick2StopKey){
  2692. if((rulesData.dbClick2StopCtrl && !e.ctrlKey) ||
  2693. (rulesData.dbClick2StopAlt && !e.altKey) ||
  2694. (rulesData.dbClick2StopShift && !e.shiftKey) ||
  2695. (rulesData.dbClick2StopMeta && !e.metaKey)){
  2696. return;
  2697. }
  2698. }
  2699. if(e.target.tagName!="BODY"){
  2700. let selStr=document.getSelection().toString();
  2701. if(selStr && selStr.trim()){
  2702. return;
  2703. }
  2704. }
  2705. if(rulesData.dbClick2Stop && (ruleParser.nextLinkHref || loadmoreBtn)){
  2706. setTimeout(()=>{
  2707. changeStop(!isPause, rulesData.hideBar);
  2708. if(!isPause){
  2709. checkScrollReach();
  2710. }
  2711. showTips(i18n(isPause?"disable":"enable"));
  2712. },10);
  2713. }
  2714. });
  2715. if(rulesData.dbClick2StopKey){
  2716. document.addEventListener('keydown', e=>{
  2717. if((rulesData.dbClick2StopCtrl && !e.ctrlKey) ||
  2718. (rulesData.dbClick2StopAlt && !e.altKey) ||
  2719. (rulesData.dbClick2StopShift && !e.shiftKey) ||
  2720. (rulesData.dbClick2StopMeta && !e.metaKey)){
  2721. return;
  2722. }
  2723. if (document.activeElement &&
  2724. (document.activeElement.tagName == 'INPUT' ||
  2725. document.activeElement.tagName == 'TEXTAREA')) {
  2726. return;
  2727. }
  2728. var key = String.fromCharCode(e.keyCode).toLowerCase();
  2729. if(rulesData.dbClick2StopKey.toLowerCase()==key){
  2730. forceState=(forceState==1?0:1);
  2731. showTips(i18n(forceState==1?"disableSiteTips":"enableSiteTips"));
  2732. if(!ruleParser.curSiteRule.url) {
  2733. storage.setItem("forceState_"+location.host, forceState);
  2734. location.reload();
  2735. }
  2736. }
  2737. });
  2738. }
  2739. }
  2740.  
  2741. function showTips(content, wordColor, backColor){
  2742. document.body.appendChild(tipsWords);
  2743. tipsWords.style.opacity=0.8;
  2744. tipsWords.innerText=content;
  2745. tipsWords.style.marginLeft=-tipsWords.offsetWidth/2+"px";
  2746. tipsWords.style.color=wordColor||0xFFFFFF;
  2747. tipsWords.style.backgroundColor=backColor||0x000;
  2748. setTimeout(()=>{tipsWords.style.opacity=0},1000);
  2749. }
  2750.  
  2751. function getLoadMore(doc){
  2752. if(ruleParser.curSiteRule.loadMore==="")return null;
  2753. let btnSel=ruleParser.curSiteRule.loadMore||".LoadMore,.load-more,.button-show-more,button[data-testid='more-results-button']",loadmoreBtn;
  2754. if(btnSel){
  2755. try{
  2756. loadmoreBtn=doc.querySelector(btnSel);
  2757. }catch(e){
  2758. loadmoreBtn=getElementByXpath(btnSel,doc,doc);
  2759. }
  2760. }
  2761. if(!loadmoreBtn){
  2762. let buttons=doc.querySelectorAll("input,button,a,div[onclick]"),loadmoreReg=/^\s*(加载更多|加載更多|load\s*more|もっと読み込む)\s*$/i;
  2763. for(let i=0;i<buttons.length;i++){
  2764. let button=buttons[i];
  2765. if(button && loadmoreReg.test(button.innerText)){
  2766. loadmoreBtn=button;
  2767. break;
  2768. }
  2769. }
  2770. }
  2771. if(loadmoreBtn && !ruleParser.curSiteRule.loadMore && loadmoreBtn.href && !/^(javascript|#)/.test(loadmoreBtn.href))loadmoreBtn=null;
  2772. return loadmoreBtn;
  2773. }
  2774.  
  2775. var hasPageNum=true;
  2776. function createPageBar(url){
  2777. let insert=ruleParser.getInsert();
  2778. if(!insert || !insert.parentNode)return;
  2779. curPage++;
  2780. let example=ruleParser.curSiteRule.insertPos==2?insert.children[0]:(insert.parentNode.children[parseInt(insert.parentNode.children.length/2)]||insert);
  2781. if (example.className=="pagetual_pageBar") {
  2782. example=example.previousElementSibling;
  2783. }
  2784. if(!example || !example.parentNode)example=insert;
  2785. let exampleStyle = _unsafeWindow.getComputedStyle(example);
  2786. let inTable=example.parentNode.tagName=="TABLE" ||
  2787. example.tagName=="TR" ||
  2788. example.tagName=="TBODY" ||
  2789. exampleStyle.display=="table-row" ||
  2790. (example.previousElementSibling && example.previousElementSibling.tagName=="TR") ||
  2791. (example.previousElementSibling && example.previousElementSibling.tagName=="TBODY");
  2792. let inLi=example.tagName=="LI" || (example.previousElementSibling && example.previousElementSibling.tagName=="LI");
  2793. if(forceState==2){
  2794. inTable=inLi=false;
  2795. }
  2796. let pageBar=document.createElement(inTable?"tr":(inLi?"li":"div"));
  2797. let upSpan=document.createElement("span");
  2798. let downSpan=document.createElement("span");
  2799. let pageText=document.createElement("a");
  2800. let pageNum;
  2801. pageBar.className="pagetual_pageBar";
  2802. pageBar.id="pagetual_pageBar"+curPage;
  2803. if(isPause){
  2804. pageBar.classList.add("stop");
  2805. }
  2806. pageBar.style.cssText=pageBarStyle;
  2807. pageBar.title=i18n(isPause?"enable":"disable");
  2808. upSpan.innerHTML=upSvg;
  2809. upSpan.children[0].style.cssText=upSvgCSS;
  2810. upSpan.title=i18n("toTop");
  2811. downSpan.innerHTML=downSvg;
  2812. downSpan.children[0].style.cssText=downSvgCSS;
  2813. downSpan.title=i18n("toBottom");
  2814. upSpan.style.cssText=initStyle;
  2815. downSpan.style.cssText=initStyle;
  2816. pageText.href=url;
  2817. pageText.style.cssText=pageTextStyle;
  2818. pageText.title=i18n("current");
  2819. pageBar.appendChild(upSpan);
  2820. pageBar.appendChild(pageText);
  2821. if(ruleParser.nextTitle){
  2822. pageText.innerHTML=ruleParser.nextTitle+" ";
  2823. pageText.title=ruleParser.nextTitle;
  2824. }
  2825. if(ruleParser.curSiteRule.pageNum || (hasPageNum && /[&\/\?](p=|page[=\/_-]?)\d+|[_-]\d+\./.test(url))){
  2826. pageText.innerHTML+="Page ";
  2827. pageNum=document.createElement("span");
  2828. pageNum.innerText=ruleParser.getPageNumFromUrl(url);
  2829. pageNum.className="pagetual_pageNum";
  2830. pageNum.title=i18n("inputPageNum");
  2831. pageNum.style.cssText=pageTextStyle;
  2832. pageNum.style.cursor="pointer";
  2833. pageNum.style.color="";
  2834. pageNum.style.marginLeft="5px";
  2835. pageNum.addEventListener("click", e=>{
  2836. let pageInput=prompt(i18n("inputPageNum"), "1");
  2837. if(pageInput){
  2838. let pageLink=ruleParser.getLinkByPage(url, pageInput);
  2839. if(pageLink){
  2840. _GM_openInTab(pageLink,{active:true});
  2841. }
  2842. }
  2843. e.preventDefault();
  2844. e.stopPropagation();
  2845. });
  2846. pageBar.appendChild(pageNum);
  2847. }else{
  2848. pageText.innerHTML+="Page "+curPage;
  2849. hasPageNum=false;
  2850. }
  2851. let preBtn=document.createElement("span");
  2852. preBtn.innerText="∧";
  2853. preBtn.title="Prev page";
  2854. preBtn.className="prev";
  2855. preBtn.style.cssText="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";
  2856. let nextBtn=document.createElement("span");
  2857. nextBtn.innerText="∨";
  2858. nextBtn.title="Next page";
  2859. nextBtn.className="next";
  2860. nextBtn.style.cssText="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";
  2861. let localPage=curPage;
  2862. preBtn.addEventListener("click", e=>{
  2863. e.stopPropagation();
  2864. e.preventDefault();
  2865. let prePageBar = document.querySelector("#pagetual_pageBar"+(localPage-1));
  2866. if (prePageBar) {
  2867. prePageBar.scrollIntoView();
  2868. document.documentElement.scrollBy(0, -50);
  2869. } else {
  2870. document.body.scrollTop=0;
  2871. document.documentElement.scrollTop=0;
  2872. }
  2873. });
  2874. nextBtn.addEventListener("click", e=>{
  2875. e.stopPropagation();
  2876. e.preventDefault();
  2877. let prePageBar=document.querySelector("#pagetual_pageBar"+(localPage+1));
  2878. if (prePageBar) {
  2879. prePageBar.scrollIntoView();
  2880. document.documentElement.scrollBy(0, -50);
  2881. } else {
  2882. document.body.scrollTop=9999999;
  2883. document.documentElement.scrollTop=9999999;
  2884. }
  2885. });
  2886. pageText.insertBefore(preBtn, pageText.firstChild);
  2887. pageText.insertBefore(nextBtn, pageText.firstChild);
  2888. pageBar.appendChild(downSpan);
  2889. let parentStyle=_unsafeWindow.getComputedStyle(example.parentNode);
  2890. let parentWidth=example.parentNode.scrollWidth||parseInt(parentStyle.width);
  2891. pageBar.style.width=parentWidth-parseInt(parentStyle.paddingLeft)-parseInt(parentStyle.paddingRight)-10+"px";
  2892. if(parentStyle.display=="grid" || parentStyle.display=="inline-grid"){
  2893. pageBar.style.gridColumnStart=1;
  2894. pageBar.style.gridColumnEnd=1+parseInt(example.parentNode.offsetWidth/example.offsetWidth);
  2895. }
  2896. if(inTable){
  2897. example=(example.tagName=="TR" || example.tagName=="TBODY")?example:example.previousElementSibling;
  2898. if(example.tagName=="TBODY")example=example.querySelector("tr");
  2899. let preTr=example;
  2900. while(preTr && preTr.children.length==0)preTr=preTr.previousElementSibling;
  2901. if(preTr)example=preTr;
  2902. let tdNum=0;
  2903. if (exampleStyle.display=="table-row") {
  2904. tdNum = example.children.length;
  2905. } else {
  2906. [].forEach.call(example.children, el=>{
  2907. if(el.tagName=="TD" || el.tagName=="TH"){
  2908. tdNum+=el.colSpan||1;
  2909. }
  2910. });
  2911. }
  2912. pageBar.style.display="table-row";
  2913. pageBar.style.backgroundColor="unset";
  2914. pageBar.style.lineHeight="20px";
  2915. pageBar.style.boxShadow="";
  2916. let td=document.createElement("td");
  2917. td.colSpan=tdNum||1;
  2918. let inTd=document.createElement("div");
  2919. inTd.style.backgroundColor="rgb(240 240 240 / 80%)";
  2920. inTd.style.borderRadius="20px";
  2921. inTd.style.padding="0 0";
  2922. inTd.style.margin="10px";
  2923. inTd.style.lineHeight="20px";
  2924. inTd.style.textAlign="center";
  2925. inTd.style.boxShadow="rgb(0 0 0 / 67%) 0px 0px 10px 0px";
  2926. inTd.appendChild(upSpan);
  2927. inTd.appendChild(pageText);
  2928. if(pageNum)inTd.appendChild(pageNum);
  2929. inTd.appendChild(downSpan);
  2930. td.appendChild(inTd);
  2931. pageBar.appendChild(td);
  2932. }else if(inLi){
  2933. example=example.tagName=="LI"?example:example.previousElementSibling;
  2934. pageBar.style.display="table-row";
  2935. pageBar.style.backgroundColor="unset";
  2936. pageBar.style.lineHeight="20px";
  2937. pageBar.style.boxShadow="";
  2938. let td=document.createElement("td");
  2939. td.colSpan=example.children.length;
  2940. let inTd=document.createElement("div");
  2941. inTd.style.backgroundColor="rgb(240 240 240 / 80%)";
  2942. inTd.style.borderRadius="20px";
  2943. inTd.style.margin="10px"
  2944. inTd.style.padding="0 0";
  2945. inTd.style.textAlign="center";
  2946. inTd.style.minWidth="150px";
  2947. inTd.appendChild(upSpan);
  2948. inTd.appendChild(pageText);
  2949. inTd.style.width=parseInt(pageBar.style.width)-20+"px";
  2950. inTd.style.boxShadow="rgb(0 0 0 / 67%) 0px 0px 10px 0px";
  2951. if(pageNum)inTd.appendChild(pageNum);
  2952. inTd.appendChild(downSpan);
  2953. td.appendChild(inTd);
  2954. pageBar.appendChild(td);
  2955. }
  2956.  
  2957. upSpan.addEventListener("click", e=>{
  2958. document.body.scrollTop=0;
  2959. document.documentElement.scrollTop=0;
  2960. e.preventDefault();
  2961. e.stopPropagation();
  2962. });
  2963. downSpan.addEventListener("click", e=>{
  2964. changeStop(true);
  2965. pageBar.title=i18n(isPause?"enable":"disable");
  2966. document.body.scrollTop=9999999;
  2967. document.documentElement.scrollTop=9999999;
  2968. e.preventDefault();
  2969. e.stopPropagation();
  2970. });
  2971. pageBar.addEventListener("click", e=>{
  2972. changeStop(!isPause);
  2973. pageBar.title=i18n(isPause?"enable":"disable");
  2974. });
  2975. pageText.addEventListener("click", e=>{
  2976. e.stopPropagation();
  2977. if (e.ctrlKey || e.altKey || e.shiftKey || e.metaKey) return;
  2978. if (e.which == 1) {
  2979. e.preventDefault();
  2980. pageBar.scrollIntoView();
  2981. document.documentElement.scrollBy(0, -50);
  2982. }
  2983. });
  2984. ruleParser.insertElement(pageBar);
  2985. if(ruleParser.curSiteRule.pageBar){
  2986. try{
  2987. ((typeof _unsafeWindow.pagetualPageBar=='undefined') ? Function("pageBar",'"use strict";' + ruleParser.curSiteRule.pageBar) : _unsafeWindow.pagetualPageBar)(pageBar);
  2988. }catch(e){
  2989. debug(e);
  2990. }
  2991. }
  2992.  
  2993. let scrollH=Math.max(document.documentElement.scrollHeight, document.body.scrollHeight);
  2994. let posEle=pageBar.nextElementSibling||pageBar;
  2995. while(posEle && !posEle.offsetParent){
  2996. posEle=posEle.previousElementSibling||posEle.parentNode;
  2997. }
  2998. if(posEle){
  2999. let actualTop = getElementTop(posEle);
  3000. bottomGap=scrollH-actualTop+(window.innerHeight||document.documentElement.clientHeight)*(ruleParser.curSiteRule.rate||1);
  3001. if(bottomGap<100)bottomGap=100;
  3002. }else{
  3003. bottomGap=1000;
  3004. }
  3005. if(rulesData.opacity==0)pageBar.style.display="none";
  3006. return pageBar;
  3007. }
  3008.  
  3009. function emuClick(btn){
  3010. if(!PointerEvent)return btn.click();
  3011. let eventParam={
  3012. isTrusted: true,
  3013. altKey: false,
  3014. azimuthAngle: 0,
  3015. bubbles: true,
  3016. button: 0,
  3017. buttons: 0,
  3018. clientX: 1,
  3019. clientY: 1,
  3020. cancelBubble: false,
  3021. cancelable: true,
  3022. composed: true,
  3023. ctrlKey: false,
  3024. defaultPrevented: false,
  3025. detail: 1,
  3026. eventPhase: 2,
  3027. fromElement: null,
  3028. height: 1,
  3029. isPrimary: false,
  3030. metaKey: false,
  3031. pointerId: 1,
  3032. pointerType: "mouse",
  3033. pressure: 0,
  3034. relatedTarget: null,
  3035. returnValue: true,
  3036. shiftKey: false,
  3037. toElement: null,
  3038. twist: 0,
  3039. which: 1
  3040. };
  3041. var mouseEvent = new PointerEvent("mousedown",eventParam);
  3042. btn.dispatchEvent(mouseEvent);
  3043. mouseEvent = new PointerEvent("mouseup",eventParam);
  3044. btn.dispatchEvent(mouseEvent);
  3045. btn.click();
  3046. }
  3047.  
  3048. var failFromIframe=0;
  3049. var inCors=false;
  3050. function requestFromIframe(url, callback){
  3051. url=url.replace(/#[^#]*/,"");
  3052. let orgPage,curPage;
  3053. let iframe = document.createElement('iframe');
  3054. iframe.name = 'pagetual-iframe';
  3055. iframe.width = '100%';
  3056. iframe.height = '0';
  3057. iframe.frameBorder = '0';
  3058. if(ruleParser.curSiteRule.sandbox!=false){
  3059. iframe.sandbox="allow-same-origin allow-scripts allow-popups allow-forms";
  3060. }
  3061. iframe.style.cssText = 'margin:0!important;padding:0!important;visibility:hidden!important;';
  3062. let waitTime=100,checkEval;
  3063. if(ruleParser.curSiteRule.wait){
  3064. if(isNaN(ruleParser.curSiteRule.wait)){
  3065. try{
  3066. checkEval=(typeof _unsafeWindow.pagetualWait=='undefined') ? Function("doc",'"use strict";' + ruleParser.curSiteRule.wait) : _unsafeWindow.pagetualWait;
  3067. }catch(e){
  3068. debug(e);
  3069. }
  3070. }else{
  3071. waitTime=ruleParser.curSiteRule.wait;
  3072. }
  3073. }
  3074. let loadedHandler=e=>{
  3075. if(e.data != 'pagetual-iframe:DOMLoaded' && e.type != 'load')return;
  3076. window.removeEventListener('message', loadedHandler, false);
  3077. iframe.removeEventListener('load', loadedHandler, false);
  3078. let tryTimes=0;
  3079. function checkIframe(){
  3080. try{
  3081. let doc=iframe.contentDocument || iframe.contentWindow.document;
  3082. let eles=ruleParser.getPageElement(doc, iframe.contentWindow);
  3083. if(checkEval && !checkEval(doc)){
  3084. setTimeout(()=>{
  3085. checkIframe();
  3086. },waitTime);
  3087. return;
  3088. }else if(eles && eles.length>0){
  3089. callback(doc, eles);
  3090. }else if(tryTimes++ < 10){
  3091. setTimeout(()=>{
  3092. checkIframe();
  3093. },waitTime);
  3094. return;
  3095. }else{
  3096. if(failFromIframe++ > 2){
  3097. failFromIframe=0;
  3098. debug("Stop as failFromIframe");
  3099. isPause=true;
  3100. callback(false, false);
  3101. }else{
  3102. callback(false, false);
  3103. }
  3104. }
  3105. }catch(e){
  3106. debug("Stop as cors");
  3107. inCors=true;
  3108. //isPause=true;
  3109. if(!ruleParser.curSiteRule.pageElement){
  3110. ruleParser.curSiteRule.pageElement=allOfBody;
  3111. ruleParser.getInsert(true);
  3112. }
  3113. ruleParser.curSiteRule.action=0;
  3114. ruleParser.nextLinkHref=url;
  3115. callback(false, false);
  3116. nextPage();
  3117. }
  3118. document.body.removeChild(iframe);
  3119. }
  3120. setTimeout(()=>{
  3121. checkIframe();
  3122. },waitTime);
  3123. };
  3124. window.addEventListener('message', loadedHandler, false);
  3125. iframe.addEventListener('load', loadedHandler, false);
  3126. iframe.src=url;
  3127. document.body.appendChild(iframe);
  3128. }
  3129.  
  3130. var emuIframe,lastActiveUrl=location.href;
  3131. function emuPage(callback){
  3132. let orgPage=null,orgContent=null,preContent=null,curPage,iframeDoc,times=0,loadmoreBtn,loadmoreEnd=false,waitTimes=10,changed=false;
  3133. function checkPage(){
  3134. if(isPause)return;
  3135. try{
  3136. iframeDoc=emuIframe.contentDocument || emuIframe.contentWindow.document;
  3137. }catch(e){
  3138. debug("Stop as cors");
  3139. isPause=true;
  3140. callback(false, false);
  3141. return;
  3142. }
  3143.  
  3144. let nextLink=ruleParser.getNextLink(iframeDoc);
  3145. let waitTime=200,checkEval;
  3146. if(ruleParser.curSiteRule.wait){
  3147. if(isNaN(ruleParser.curSiteRule.wait)){
  3148. try{
  3149. checkEval=(typeof _unsafeWindow.pagetualWait=='undefined') ? Function("doc",'"use strict";' + ruleParser.curSiteRule.wait) : _unsafeWindow.pagetualWait;
  3150. }catch(e){
  3151. debug(e);
  3152. }
  3153. }else{
  3154. waitTime=ruleParser.curSiteRule.wait;
  3155. }
  3156. }
  3157.  
  3158. if(!orgPage){
  3159. if(!loadmoreEnd){
  3160. loadmoreBtn=getLoadMore(iframeDoc);
  3161. if(loadmoreBtn && isVisible(loadmoreBtn, iframeDoc.defaultView)){
  3162. emuClick(loadmoreBtn);
  3163. let intv=setInterval(()=>{
  3164. loadmoreBtn=getLoadMore(iframeDoc);
  3165. if(!loadmoreBtn || !loadmoreBtn.parentNode || !isVisible(loadmoreBtn, iframeDoc.defaultView)){
  3166. clearInterval(intv);
  3167. loadmoreEnd=true;
  3168. setTimeout(()=>{
  3169. checkPage();
  3170. },500);
  3171. }else{
  3172. emuClick(loadmoreBtn);
  3173. }
  3174. },200);
  3175. return;
  3176. }else{
  3177. loadmoreEnd=true;
  3178. }
  3179. }
  3180. let pageEle=ruleParser.getPageElement(iframeDoc, iframeDoc.defaultView, true);
  3181. if(checkEval && !checkEval(iframeDoc)){
  3182. setTimeout(()=>{
  3183. checkPage();
  3184. },waitTime);
  3185. return;
  3186. }else if(!nextLink || !pageEle || pageEle.length==0){
  3187. if(waitTimes-->0){
  3188. setTimeout(()=>{
  3189. checkPage();
  3190. },waitTime);
  3191. return;
  3192. }
  3193. }
  3194. orgPage=pageEle;
  3195. if(!orgPage || orgPage.length==0){
  3196. debug("Stop as no page when emu");
  3197. isPause=true;
  3198. callback(false, false);
  3199. return;
  3200. }
  3201. if(orgPage && orgPage[0].tagName=="UL")orgPage=orgPage[0].children;
  3202. if(orgPage && nextLink){
  3203. orgPage=orgPage[parseInt(orgPage.length/2)];
  3204. orgContent=orgPage.innerText;
  3205. preContent=orgContent;
  3206. if(!isVisible(nextLink, iframeDoc.defaultView)){
  3207. debug("Stop as next hide when emu");
  3208. isPause=true;
  3209. callback(false, false);
  3210. }else{
  3211. emuClick(nextLink);
  3212. setTimeout(()=>{
  3213. checkPage();
  3214. },500);
  3215. }
  3216. }else{
  3217. debug("Stop as no next when emu");
  3218. isPause=true;
  3219. callback(false, false);
  3220. }
  3221. return;
  3222. }
  3223. if(times++ > 20){
  3224. debug("Stop as timeout when emu");
  3225. isPause=true;
  3226. callback(false, false);
  3227. return;
  3228. }
  3229. let eles=ruleParser.getPageElement(iframeDoc, iframeDoc.defaultView, true),checkItem;
  3230. if(eles && eles.length>0){
  3231. checkItem=eles;
  3232. if(eles[0].tagName=="UL"){
  3233. checkItem=eles[0].children;
  3234. }
  3235. checkItem=checkItem[parseInt(checkItem.length/2)];
  3236. }
  3237. if(!checkItem || (checkEval && !checkEval(iframeDoc))){
  3238. setTimeout(()=>{
  3239. checkPage();
  3240. },waitTime);
  3241. }else{
  3242. if(orgPage!=checkItem || checkItem.innerText!=preContent){
  3243. changed=true;
  3244. orgPage=checkItem;
  3245. preContent=checkItem.innerText;
  3246. setTimeout(()=>{
  3247. checkPage();
  3248. },waitTime);
  3249. }else if(changed){
  3250. if (orgContent == preContent) {
  3251. debug("Stop as same content");
  3252. isPause=true;
  3253. callback(false, false);
  3254. } else {
  3255. callback(iframeDoc, eles);
  3256. }
  3257. }else{
  3258. setTimeout(()=>{
  3259. checkPage();
  3260. },waitTime);
  3261. }
  3262. }
  3263. }
  3264. if(!emuIframe){
  3265. let loaded=false;
  3266. emuIframe = document.createElement('iframe');
  3267. emuIframe.name = 'pagetual-iframe';
  3268. if(ruleParser.curSiteRule.sandbox!=false){
  3269. emuIframe.sandbox="allow-same-origin allow-scripts allow-popups allow-forms";
  3270. }
  3271. emuIframe.width = '100%';
  3272. emuIframe.height = '0';
  3273. emuIframe.frameBorder = '0';
  3274. emuIframe.style.cssText = 'margin:0!important;padding:0!important;visibility:hidden!important;';
  3275. emuIframe.addEventListener("load", e=>{
  3276. setTimeout(()=>{
  3277. try{
  3278. iframeDoc=emuIframe.contentDocument || emuIframe.contentWindow.document;
  3279. }catch(e){
  3280. debug("Stop as cors");
  3281. isPause=true;
  3282. callback(false, false);
  3283. return;
  3284. }
  3285. let code=ruleParser.curSiteRule.init;
  3286. if(code){
  3287. try{
  3288. Function('doc','win','iframe','"use strict";' + code)(iframeDoc, iframeDoc.defaultView, emuIframe);
  3289. }catch(e){
  3290. debug(e);
  3291. }
  3292. }
  3293. if(loaded)return;
  3294. loaded=true;
  3295. checkPage();
  3296. },500);
  3297. });
  3298. emuIframe.src=lastActiveUrl.replace(/#[^#]*/,"");
  3299. document.body.appendChild(emuIframe);
  3300. }else{
  3301. checkPage();
  3302. }
  3303. }
  3304.  
  3305. var scrollToResizeInited = false;
  3306. var resizePool = [];
  3307. function scrollToResize() {
  3308. if (scrollToResizeInited) return;
  3309. scrollToResizeInited = true;
  3310. var scrollingToResize = false;
  3311. document.addEventListener("scroll", e => {
  3312. if (scrollingToResize) return;
  3313. else {
  3314. scrollingToResize = true;
  3315. setTimeout(() => {scrollingToResize = false}, 500);
  3316. }
  3317. resizePool.forEach(resizeArr => {
  3318. let iframe = resizeArr[1]();
  3319. let frameDoc = resizeArr[2]();
  3320. if(ruleParser.curSiteRule.singleUrl){
  3321. iframe.style.height=frameDoc.body.scrollHeight+"px";
  3322. iframe.style.width=frameDoc.body.scrollWidth+"px";
  3323. }else{
  3324. let pageEle = resizeArr[0]();
  3325. if(pageEle){
  3326. let targetElement = pageEle[0];
  3327. if(pageEle.length > 1){
  3328. targetElement = targetElement.parentNode;
  3329. }
  3330. iframe.style.height=targetElement.scrollHeight+"px";
  3331. frameDoc.documentElement.scrollTop = 0;
  3332. frameDoc.documentElement.scrollLeft = 0;
  3333. while(targetElement && targetElement.offsetParent){
  3334. targetElement.offsetParent.scrollTop = targetElement.offsetTop;
  3335. if(targetElement.offsetParent.scrollTop == 0){
  3336. frameDoc.documentElement.scrollTop += targetElement.offsetTop;
  3337. }
  3338. targetElement.offsetParent.scrollLeft = targetElement.offsetLeft;
  3339. if(targetElement.offsetParent.scrollLeft == 0){
  3340. frameDoc.documentElement.scrollLeft += targetElement.offsetLeft;
  3341. }
  3342. targetElement = targetElement.offsetParent;
  3343. }
  3344. }
  3345. }
  3346. });
  3347. });
  3348. }
  3349.  
  3350. function forceIframe(url, callback){
  3351. url=url.replace(/#[^#]*/,"");
  3352. let curIframe = document.createElement('iframe'),iframeDoc;
  3353. let setPosition = ()=>{
  3354. let getIframe = () => {
  3355. return curIframe;
  3356. };
  3357. let getFrameDoc = () => {
  3358. return iframeDoc;
  3359. };
  3360. if(ruleParser.curSiteRule.singleUrl){
  3361. resizePool.push([() => {}, getIframe, getFrameDoc]);
  3362. }else{
  3363. let pageElement = ruleParser.getPageElement(iframeDoc,iframeDoc.defaultView);
  3364. let getPageEle = () => {
  3365. if (!pageElement) {
  3366. pageElement = ruleParser.getPageElement(iframeDoc,iframeDoc.defaultView);
  3367. }
  3368. return pageElement;
  3369. };
  3370. resizePool.push([getPageEle, getIframe, getFrameDoc]);
  3371. }
  3372. };
  3373. curIframe.name = 'pagetual-iframe';
  3374. curIframe.sandbox="allow-same-origin allow-scripts allow-popups allow-forms";
  3375. curIframe.frameBorder = '0';
  3376. curIframe.scrolling="no";
  3377. 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;';
  3378. curIframe.addEventListener("load", e=>{
  3379. try{
  3380. iframeDoc=curIframe.contentDocument || curIframe.contentWindow.document;
  3381. }catch(e){
  3382. debug("Stop as cors");
  3383. isPause=true;
  3384. callback(false, false);
  3385. return;
  3386. }
  3387. ruleParser.insertPage(iframeDoc, [], url, null, true);
  3388. callback(curIframe, true);
  3389. let css=ruleParser.curSiteRule.css;
  3390. if(css){
  3391. let styleEle=iframeDoc.createElement("style");
  3392. styleEle.innerHTML=css;
  3393. iframeDoc.head.appendChild(styleEle);
  3394. }
  3395. setPosition();
  3396. let code=ruleParser.curSiteRule.init;
  3397. if(code){
  3398. try{
  3399. Function('doc','win','iframe','"use strict";' + code)(iframeDoc,iframeDoc.defaultView,curIframe);
  3400. }catch(e){
  3401. debug(e);
  3402. }
  3403. }
  3404. });
  3405. let inAction=false,checkTimes=0;
  3406. let forceRefresh=e=>{
  3407. if(inAction || !iframeDoc)return;
  3408. inAction=true;
  3409. let foundNext=()=>{
  3410. document.removeEventListener("scroll", forceRefresh);
  3411. }
  3412. setTimeout(()=>{
  3413. inAction=false;
  3414. if(!ruleParser.nextLinkHref){
  3415. checkTimes++;
  3416. ruleParser.getNextLink(iframeDoc);
  3417. if(ruleParser.nextLinkHref){
  3418. foundNext();
  3419. }else if(checkTimes>=10){
  3420. foundNext();
  3421. }
  3422. }else{
  3423. foundNext();
  3424. }
  3425. },50);
  3426. };
  3427. document.addEventListener("scroll", forceRefresh);
  3428. curIframe.src=url;
  3429. let insert=ruleParser.getInsert();
  3430. if(ruleParser.curSiteRule.singleUrl || forceState==2){
  3431. document.body.appendChild(loadingDiv);
  3432. document.body.appendChild(curIframe);
  3433. }else{
  3434. ruleParser.insertElement(curIframe);
  3435. }
  3436. scrollToResize();
  3437. return curIframe;
  3438. }
  3439.  
  3440. function loadPageOver(){
  3441. isLoading=false;
  3442. if(loadingDiv.parentNode){
  3443. loadingDiv.parentNode.removeChild(loadingDiv);
  3444. }
  3445. /*setTimeout(()=>{
  3446. let scrollH=Math.max(document.documentElement.scrollHeight, document.body.scrollHeight);
  3447. if(scrollH <= (window.innerHeight || document.documentElement.clientHeight)){
  3448. nextPage();
  3449. }
  3450. },1);*/
  3451. }
  3452.  
  3453. var tryTimes = 0;
  3454.  
  3455. function nextPage(){
  3456. if(isPause || isLoading || forceState==1)return;
  3457. if(ruleParser.curSiteRule.delay){
  3458. try{
  3459. let checkDelay=((typeof _unsafeWindow.pagetualDelay=='undefined') ? Function('"use strict";' + ruleParser.curSiteRule.delay) : _unsafeWindow.pagetualDelay)();
  3460. if(!checkDelay)return;
  3461. }catch(e){
  3462. debug(e);
  3463. }
  3464. }
  3465. let nextLink=ruleParser.nextLinkHref;
  3466. if(!nextLink){
  3467. if(curPage==1){
  3468. ruleParser.getNextLink(document);
  3469. nextLink=ruleParser.nextLinkHref;
  3470. }
  3471. if(!nextLink){
  3472. isLoading=true;
  3473. if(curPage==1 && (ruleParser.curSiteRule.pinUrl || tryTimes++ <= 10)){
  3474. setTimeout(()=>{isLoading=false},500);
  3475. }
  3476. return;
  3477. }
  3478. }
  3479. let pvGallery=document.querySelector("span.pv-gallery-container");
  3480. if(pvGallery && pvGallery.style.display!="none")return;
  3481. let insert=ruleParser.getInsert();
  3482. if(insert){
  3483. let isJs=/^(javascript|#)/.test(nextLink.replace(location.href,""));
  3484. if(!isJs){
  3485. emuIframe=null;
  3486. lastActiveUrl=nextLink;
  3487. }
  3488. if(location.protocol=="https:" && /^http:/.test(nextLink)){
  3489. nextLink=nextLink.replace(/^http/,"https");
  3490. }
  3491. isLoading=true;
  3492. ruleParser.insertElement(loadingDiv);
  3493. loadingDiv.style.cssText=loadingCSS;
  3494. let sleep=ruleParser.curSiteRule.sleep||0;
  3495. setTimeout(()=>{
  3496. if(ruleParser.curSiteRule.pageElementByJs){
  3497. var over=ele=>{
  3498. loadPageOver();
  3499. if(ele){
  3500. createPageBar(nextLink);
  3501. ruleParser.insertPage(null, ele, nextLink, null, true);
  3502. if(autoLoadNum>=0){
  3503. if(autoLoadNum!=0 && --autoLoadNum==0){
  3504. autoLoadNum=-1;
  3505. }else{
  3506. nextPage();
  3507. }
  3508. }
  3509. }else{
  3510. debug("Stop as no page when get by js");
  3511. isPause=true;
  3512. }
  3513. };
  3514. try{
  3515. ((typeof _unsafeWindow.pagetualPageElementByJs=='undefined') ? Function("over",'"use strict";' + ruleParser.curSiteRule.pageElementByJs) : _unsafeWindow.pagetualPageElementByJs)(over);
  3516. }catch(e){
  3517. debug(e);
  3518. }
  3519. }else if((forceState==3||ruleParser.curSiteRule.action==1) && !isJs){
  3520. requestFromIframe(nextLink, (doc, eles)=>{
  3521. loadPageOver();
  3522. if(eles){
  3523. ruleParser.insertPage(doc, eles, nextLink, ()=>{
  3524. createPageBar(nextLink);
  3525. }, true);
  3526. if(autoLoadNum>=0){
  3527. if(autoLoadNum!=0 && --autoLoadNum==0){
  3528. autoLoadNum=-1;
  3529. }else{
  3530. nextPage();
  3531. }
  3532. }
  3533. }
  3534. });
  3535. }else if((forceState==2||ruleParser.curSiteRule.action==2) && !isJs){
  3536. forceIframe(nextLink, (iframe, eles)=>{
  3537. loadPageOver();
  3538. let pageBar=createPageBar(nextLink);
  3539. if(pageBar)iframe.parentNode.insertBefore(pageBar, iframe);
  3540. if(autoLoadNum>=0){
  3541. if(autoLoadNum!=0 && --autoLoadNum==0){
  3542. autoLoadNum=-1;
  3543. }else{
  3544. nextPage();
  3545. }
  3546. }
  3547. });
  3548. }else{
  3549. if(!isJs){
  3550. requestDoc(nextLink, (eles)=>{
  3551. loadPageOver();
  3552. if(eles){
  3553. createPageBar(nextLink);
  3554. if(autoLoadNum>=0){
  3555. if(autoLoadNum!=0 && --autoLoadNum==0){
  3556. autoLoadNum=-1;
  3557. }else{
  3558. nextPage();
  3559. }
  3560. }
  3561. }
  3562. });
  3563. }else{
  3564. emuPage((doc, eles)=>{
  3565. loadPageOver();
  3566. if(eles){
  3567. ruleParser.insertPage(doc, eles, "", ()=>{
  3568. createPageBar(nextLink);
  3569. }, true);
  3570. if(autoLoadNum>=0){
  3571. if(autoLoadNum!=0 && --autoLoadNum==0){
  3572. autoLoadNum=-1;
  3573. }else{
  3574. nextPage();
  3575. }
  3576. }
  3577. }
  3578. });
  3579. }
  3580. }
  3581. },sleep);
  3582. }
  3583. }
  3584.  
  3585. function init(){
  3586. initRules(()=>{
  3587. initPage();
  3588. });
  3589. }
  3590.  
  3591. function visibilitychangeHandler(){
  3592. document.removeEventListener('visibilitychange', visibilitychangeHandler);
  3593. init();
  3594. }
  3595.  
  3596. setTimeout(()=>{
  3597. if (document.hidden) {
  3598. document.addEventListener('visibilitychange', visibilitychangeHandler);
  3599. } else {
  3600. init();
  3601. }
  3602. },100);
  3603. })();