东方永页机

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

当前为 2022-05-11 提交的版本,查看 最新版本

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