东方永页机

自动加载并拼接下一分页内容(适用于论坛、漫画站、小说站、资讯站、博客等),无需规则支持所有网页

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

  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.5.3.3
  14. // @description Most compatible Auto pager script ever! Simply auto loading paginated web pages.
  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. // @include http://*
  26. // @include https://*
  27. // @license MIT
  28. // @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==
  29. // @grant GM_xmlhttpRequest
  30. // @grant GM_registerMenuCommand
  31. // @grant GM_notification
  32. // @grant GM_getValue
  33. // @grant GM_setValue
  34. // @grant GM_addStyle
  35. // @grant GM_openInTab
  36. // @grant GM_deleteValue
  37. // @grant GM.xmlHttpRequest
  38. // @grant GM.registerMenuCommand
  39. // @grant GM.notification
  40. // @grant GM.getValue
  41. // @grant GM.setValue
  42. // @grant GM.addStyle
  43. // @grant GM.openInTab
  44. // @grant GM.deleteValue
  45. // @supportURL https://github.com/hoothin/UserScripts/issues
  46. // @connect wedata.net
  47. // @connect githubusercontent.com
  48. // @run-at document-idle
  49. // @exclude http://www.toodledo.com/tasks/*
  50. // @exclude http*://maps.google.com*/*
  51. // @exclude *://www.google.*/_/chrome/newtab*
  52. // @exclude *://mega.*/*
  53. // @exclude *://*.mega.*/*
  54. // @exclude *://*.youku.com/v_*
  55. // @exclude *://*pan.baidu.com
  56. // @exclude *://*.iqiyi.com/v_*
  57. // @exclude *://*.iqiyi.com/w_*
  58. // @exclude *://*.iqiyi.com/a_*
  59. // @exclude *://*.le.com/ptv/vplay/*
  60. // @exclude *://v.qq.com/x/cover/*
  61. // @exclude *://v.qq.com/x/page/*
  62. // @exclude *://v.qq.com/tv/*
  63. // @exclude *://*.tudou.com/listplay/*
  64. // @exclude *://*.tudou.com/albumplay/*
  65. // @exclude *://*.tudou.com/programs/view/*
  66. // @exclude *://*.mgtv.com/b/*
  67. // @exclude *://film.sohu.com/album/*
  68. // @exclude *://tv.sohu.com/v/*
  69. // @exclude *://*.bilibili.com/video/*
  70. // @exclude *://*.bilibili.com/bangumi/play/*
  71. // @exclude *://*.baofeng.com/play/*
  72. // @exclude *://vip.pptv.com/show/*
  73. // @exclude *://v.pptv.com/show/*
  74. // @exclude *://www.le.com/ptv/vplay/*
  75. // @exclude *://www.wasu.cn/Play/show/*
  76. // @exclude *://m.v.qq.com/*
  77. // @exclude *://m.iqiyi.com/*
  78. // @exclude *://m.youku.com/alipay_video/*
  79. // @exclude *://m.mgtv.com/b/*
  80. // @exclude *://m.tv.sohu.com/v/*
  81. // @exclude *://m.film.sohu.com/album/*
  82. // @exclude *://m.le.com/ptv/vplay/*
  83. // @exclude *://m.pptv.com/show/*
  84. // @exclude *://m.acfun.cn/v/*
  85. // @exclude *://m.bilibili.com/video/*
  86. // @exclude *://m.bilibili.com/anime/*
  87. // @exclude *://m.bilibili.com/bangumi/play/*
  88. // @exclude *://m.wasu.cn/Play/show/*
  89. // @exclude *://www.youtube.com
  90. // @exclude *://www.youtube.com/
  91. // @exclude *://www.youtube.com/watch*
  92. // @exclude *://baike.baidu.com/*
  93. // @exclude *://*.instagram.com/*
  94. // @exclude *://order.jd.com/*
  95. // @exclude *://pagetual.hoothin.com/*
  96. // @exclude *://hoothin.github.io/PagetualGuide/*
  97. // @connect *
  98. // ==/UserScript==
  99.  
  100. (function() {
  101. 'use strict';
  102.  
  103. if (window.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) {
  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. };
  169. break;
  170. case "zh-TW":
  171. case "zh-HK":
  172. config={
  173. enableDebug:"調試模式",
  174. disable:"暫時禁用",
  175. disableSite:"在此站禁用",
  176. enable:"啟用翻頁",
  177. toTop:"回到頂部",
  178. toBottom:"前往頁尾",
  179. current:"當前頁",
  180. forceIframe:"強制拼接",
  181. cancelForceIframe:"取消强制拼接",
  182. configure:"打開配置頁",
  183. firstUpdate:"點擊此處初始化規則",
  184. update:"更新規則",
  185. click2update:"點擊立即更新規則",
  186. loadNow:"立即翻頁",
  187. loadConfirm:"要翻几頁?(0為不間斷)",
  188. noNext:"沒有找到下一頁,請新建規則",
  189. passSec:"更新于 #t# 秒前",
  190. passMin:"更新于 #t# 分鐘前",
  191. passHour:"更新于 #t# 小時前",
  192. passDay:"更新于 #t# 天前",
  193. cantDel:"無法刪除内置規則",
  194. confirmDel:"是否確認要刪除此規則?",
  195. updateSucc:"更新成功",
  196. beginUpdate:"正在更新,請稍候",
  197. customUrls:"導入規則url,一行一條,AutoPagerize 格式規則需要以\"0|\"開頭",
  198. customRules:"輸入【東方永頁機】格式的自定義規則",
  199. save:"存儲設置",
  200. loadingText:"少女祈禱中...",
  201. opacity:"分頁隔條不透明值",
  202. hideBar:"空白處雙擊隱藏分頁隔條",
  203. dbClick2Stop:"空白處雙擊暫停翻頁",
  204. sortTitle:"排序在下次更新規則後生效",
  205. autoRun:"自動啓用",
  206. inputPageNum:"輸入頁碼跳轉",
  207. enableHistory:"翻頁后寫入歷史記錄"
  208. };
  209. break;
  210. case "ja":
  211. config = {
  212. enableDebug:"デバッグモード",
  213. disable: "一時的に無効にする",
  214. disableSite:"このサイト無効",
  215. enable: "ページめくりを有効にする",
  216. toTop: "トップに戻る",
  217. toBottom: "ページの下部に移動",
  218. current: "現在のページ",
  219. forceIframe: "強制ステッチ",
  220. cancelForceIframe: "強制ステッチをキャンセル",
  221. configure: "設定ページを開く",
  222. firstUpdate:"ここをクリックしてルールを初期化します",
  223. update: "更新ルール",
  224. click2update:"今すぐルールを更新してください",
  225. loadNow:"今すぐページをめくる",
  226. loadConfirm:"数ページめくりたいですか?(0は途切れない)",
  227. noNext:"次のページが見つかりません、新しいルールを作成してください",
  228. passSec: "#t#秒前に更新",
  229. passMin: "#t#分前に更新",
  230. passHour: "#t#時間前に更新",
  231. passDay: "#t#日前に更新",
  232. cantDel: "組み込みルールを削除できません",
  233. confirmDel: "このルールを削除してもよろしいですか?",
  234. updateSucc: "更新に成功しました",
  235. beginUpdate: "更新中、お待ちください",
  236. customUrls: "インポートルールのURL、1行に1つ、AutoPagerizeフォーマットルールは\"0|\"で始まる必要があります",
  237. customRules: "【東方永頁機】の形式でカスタムルールを入力してください",
  238. save: "設定を保存",
  239. loadingText: "少女祈祷中...",
  240. opacity:"ページネーションバーの不透明値",
  241. hideBar:"空白部分をダブルクリックして、ページ区切り文字を非表示にします",
  242. dbClick2Stop:"空白部分をダブルクリックしてページめくりを一時停止します",
  243. sortTitle:"並べ替えは、次のルールの更新後に有効になります",
  244. autoRun:"自動的に有効",
  245. inputPageNum:"ジャンプするページ番号を入力",
  246. enableHistory:"ページめくり後の履歴を書く"
  247. };
  248. break;
  249. default:
  250. config={
  251. enableDebug:"Enable debug output",
  252. disable:"Disable",
  253. disableSite:"Disable on the site",
  254. enable:"Enable",
  255. toTop:"To Top",
  256. toBottom:"To Bottom",
  257. current:"Current Page",
  258. forceIframe:"Force to join",
  259. cancelForceIframe:"Cancel Force join",
  260. configure:"Configure",
  261. firstUpdate:"Click here to initialize the rules",
  262. update:"Update rules",
  263. click2update:"Click to update rules from url now",
  264. loadNow:"Load next now",
  265. loadConfirm:"How much pages do you want to load? (0 means infinite)",
  266. noNext:"No next link found, please create a new rule",
  267. passSec:"Updated #t# seconds ago",
  268. passMin:"Updated #t# minutes ago",
  269. passHour:"Updated #t# hours ago",
  270. passDay:"Updated #t# days ago",
  271. cantDel:"Can't delete buildin rules",
  272. confirmDel:"Are you sure you want to delete this rule?",
  273. updateSucc:"Update succeeded",
  274. beginUpdate:"Begin update, wait a minute please",
  275. customUrls:"Import rule url, One url per line, rules on AutoPagerize format need to start with \"0|\"",
  276. customRules:"Input custom rules with [Pagetual] format",
  277. save:"Save",
  278. loadingText:"Shojo Now Loading...",
  279. opacity:"Pagination spacer opacity",
  280. hideBar:"Double-click on the blank space to hide the paging spacer",
  281. dbClick2Stop:"Double-click on the blank space to stop",
  282. sortTitle:"Sorting takes effect after the next rule update",
  283. autoRun:"Auto run",
  284. inputPageNum:"Enter page number to jump",
  285. enableHistory:"Write history after page turning"
  286. };
  287. break;
  288. }
  289. return config[name]?config[name].replace("#t#",param):name;
  290. };
  291.  
  292. var enableDebug=true;
  293. var debug=str=>{
  294. if(enableDebug){
  295. console.debug(str);
  296. }
  297. };
  298.  
  299. var _GM_xmlhttpRequest,_GM_registerMenuCommand,_GM_notification,_GM_addStyle,_GM_openInTab;
  300. if(typeof GM_xmlhttpRequest!='undefined'){
  301. _GM_xmlhttpRequest=GM_xmlhttpRequest;
  302. }else if(typeof GM!='undefined' && typeof GM.xmlHttpRequest!='undefined'){
  303. _GM_xmlhttpRequest=GM.xmlHttpRequest;
  304. }else{
  305. _GM_xmlhttpRequest=(f)=>{fetch(f.url).then(response=>response.text()).then(data=>{let res={response:data};f.onload(res)}).catch(f.onerror())};
  306. }
  307. if(typeof GM_registerMenuCommand!='undefined'){
  308. _GM_registerMenuCommand=GM_registerMenuCommand;
  309. }else if(typeof GM!='undefined' && typeof GM.registerMenuCommand!='undefined'){
  310. _GM_registerMenuCommand=GM.registerMenuCommand;
  311. }else{
  312. _GM_registerMenuCommand=(s,f)=>{};
  313. }
  314. if(typeof GM_notification!='undefined'){
  315. _GM_notification=GM_notification;
  316. }else if(typeof GM!='undefined' && typeof GM.notification!='undefined'){
  317. _GM_notification=GM.notification;
  318. }else{
  319. _GM_notification=(s)=>{alert(s)};
  320. }
  321. if(typeof GM_openInTab!='undefined'){
  322. _GM_openInTab=GM_openInTab;
  323. }else if(typeof GM!='undefined' && typeof GM.openInTab!='undefined'){
  324. _GM_openInTab=GM.openInTab;
  325. }else{
  326. _GM_openInTab=(s,t)=>{window.open(s)};
  327. }
  328. if(typeof GM_addStyle!='undefined'){
  329. _GM_addStyle=GM_addStyle;
  330. }else if(typeof GM!='undefined' && typeof GM.addStyle!='undefined'){
  331. _GM_addStyle=GM.addStyle;
  332. }else{
  333. _GM_addStyle=cssStr=>{
  334. let styleEle=document.createElement("style");
  335. styleEle.innerHTML=cssStr;
  336. document.head.appendChild(styleEle);
  337. };
  338. }
  339. var _unsafeWindow=(typeof unsafeWindow=='undefined')?window:unsafeWindow;//兼容 ios userscripts 的寫法
  340. var storage={
  341. supportGM: typeof GM_getValue=='function' && typeof GM_getValue('a','b')!='undefined',
  342. supportGMPromise: typeof GM!='undefined' && typeof GM.getValue=='function' && typeof GM.getValue('a','b')!='undefined',
  343. mxAppStorage:(function(){
  344. try{
  345. return window.external.mxGetRuntime().storage;
  346. }catch(e){
  347. }
  348. })(),
  349. operaUJSStorage:(function(){
  350. try{
  351. return window.opera.scriptStorage;
  352. }catch(e){
  353. }
  354. })(),
  355. setItem:function(key,value){
  356. if(this.operaUJSStorage){
  357. this.operaUJSStorage.setItem(key,value);
  358. }else if(this.mxAppStorage){
  359. this.mxAppStorage.setConfig(key,value);
  360. }else if(this.supportGM){
  361. GM_setValue(key,value);
  362. if(value==="" && typeof GM_deleteValue!='undefined'){
  363. GM_deleteValue(key);
  364. }
  365. }else if(this.supportGMPromise){
  366. GM.setValue(key,value);
  367. if(value==="" && typeof GM!='undefined' && typeof GM.deleteValue!='undefined'){
  368. GM.deleteValue(key);
  369. }
  370. }else if(window.localStorage){
  371. window.localStorage.setItem(key,value);
  372. }
  373. },
  374. getItem:function(key,cb){
  375. var value;
  376. if(this.operaUJSStorage){
  377. value=this.operaUJSStorage.getItem(key);
  378. }else if(this.mxAppStorage){
  379. value=this.mxAppStorage.getConfig(key);
  380. }else if(this.supportGM){
  381. value=GM_getValue(key);
  382. }else if(this.supportGMPromise){
  383. value=GM.getValue(key).then(v=>{cb(v)});
  384. return;
  385. }else if(window.localStorage){
  386. value=window.localStorage.getItem(key);
  387. };
  388. cb(value);
  389. }
  390. };
  391. var rulesData={},ruleUrls,updateDate,configPage="https://github.com/hoothin/UserScripts/tree/master/Pagetual";
  392. var allOfBody="body>*";
  393. _GM_registerMenuCommand(i18n("configure"), ()=>{
  394. _GM_openInTab(configPage,{active:true});
  395. });
  396.  
  397. function getElementByXpath(xpath, contextNode, doc){
  398. doc = doc || document;
  399. contextNode = contextNode || doc;
  400. try {
  401. var result = doc.evaluate(xpath, contextNode, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
  402. return result.singleNodeValue && result.singleNodeValue.nodeType === 1 && result.singleNodeValue;
  403. } catch (err) {
  404. throw new Error(`Invalid xpath: ${xpath}`);
  405. }
  406. }
  407.  
  408. function getAllElementsByXpath(xpath, contextNode, doc){
  409. doc = doc || document;
  410. contextNode = contextNode || doc;
  411. var result = [];
  412. try {
  413. var query = doc.evaluate(xpath, contextNode, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  414. for (var i = 0; i < query.snapshotLength; i++) {
  415. var node = query.snapshotItem(i);
  416. if (node.nodeType === 1) result.push(node);
  417. }
  418. } catch (err) {
  419. throw new Error(`Invalid xpath: ${xpath}`);
  420. }
  421. return result;
  422. }
  423.  
  424. class RuleParser {
  425. constructor() {
  426. this.hpRules=[];
  427. this.customRules=[];
  428. this.rules=[];
  429. this.pageDoc=document;
  430. this.nextLinkHref=null;
  431. this.curUrl=location.href;
  432. this.curSiteRule={};
  433. }
  434.  
  435. initSavedRules(callback){
  436. var self=this;
  437. storage.getItem("hpRules", hpRules=>{
  438. if(hpRules)self.hpRules=hpRules;
  439. storage.getItem("customRules", customRules=>{
  440. if(customRules)self.customRules=customRules;
  441. storage.getItem("rules", rules=>{
  442. if(rules)this.rules=rules;
  443. callback();
  444. });
  445. });
  446. });
  447. }
  448.  
  449. saveCurSiteRule(){
  450. if(!this.curSiteRule || !this.curSiteRule.url || this.curSiteRule.singleUrl)return;
  451. this.hpRules=this.hpRules.filter(item=>{return item&&item.url!=this.curSiteRule.url});
  452. this.hpRules.unshift(this.curSiteRule);
  453. if(this.hpRules.length>30){
  454. this.hpRules.pop();
  455. }
  456. storage.setItem("hpRules", this.hpRules);
  457. }
  458.  
  459. requestJSON(url, callback){
  460. _GM_xmlhttpRequest({
  461. url: url,
  462. method: 'GET',
  463. timeout: 20000,
  464. onload: function(res) {
  465. let json=null;
  466. try{
  467. json=JSON.parse(res.response||res.responseText);
  468. }catch(e){
  469. debug(e);
  470. }
  471. callback(json);
  472. },
  473. onerror: function(e) {
  474. callback(null, e);
  475. },
  476. ontimeout: function(e) {
  477. callback(null, e);
  478. }
  479. });
  480. }
  481.  
  482. formatRule(item, type, from){
  483. switch(type){
  484. case 0:
  485. return {
  486. from:from,
  487. type:type,
  488. name:item.name,
  489. action:item.data.forceIframe=="true"?1:0,
  490. url:item.data.url,
  491. pageElement:item.data.pageElement,
  492. nextLink:item.data.nextLink,
  493. insert:item.data.insertBefore,
  494. insertPos:1,
  495. updatedAt:item.data.updated_at,
  496. css:item.data.Stylus+item.data.CSS,
  497. pageAction:item.data.bookmarklet
  498. };
  499. break;
  500. case 1:
  501. default:
  502. item.from=from;
  503. if(typeof(item.type) == "undefined")item.type=type;
  504. return item;
  505. break;
  506. }
  507. return null;
  508. }
  509.  
  510. addRuleByUrl(url, type, from, callback) {
  511. if(url.indexOf("?")==-1){
  512. url=url+"?"+Date.now();
  513. }else{
  514. url=url+"&"+Date.now();
  515. }
  516. this.requestJSON(url, (json,err)=>{
  517. if(!json){
  518. debug("Update "+url+" rules fail!");
  519. debug(err);
  520. }
  521. this.addRules(json, type, from);
  522. callback(json, err);
  523. });
  524. }
  525.  
  526. addRules(rules, type, from) {
  527. if(rules && rules.length>0){
  528. this.rules=this.rules.filter(item=>{return item.from!=from});
  529. rules.forEach(item=>{
  530. let rule=this.formatRule(item, type, from);
  531. if(rule){
  532. this.rules.unshift(rule);
  533. }
  534. });
  535. }
  536. }
  537.  
  538. getRule(callback) {
  539. if(this.curSiteRule && this.curSiteRule.url){
  540. return this.curSiteRule;
  541. }
  542. var self=this;
  543.  
  544. function setRule(r){
  545. self.curSiteRule=r;
  546. debug(r);
  547. callback();
  548. }
  549.  
  550. function ruleMatch(r){
  551. let pageElement,nextLink,insert;
  552. if(r.pageElement)pageElement=r.type==0?getElementByXpath(r.pageElement):document.querySelector(r.pageElement);
  553. if(r.nextLink)nextLink=r.type==0?getElementByXpath(r.nextLink):document.querySelector(r.nextLink);
  554. if(r.insert)insert=r.type==0?getElementByXpath(r.insert):document.querySelector(r.insert);
  555. return !((r.pageElement && !pageElement) ||
  556. (r.nextLink && !nextLink) ||
  557. (r.insert && !insert));
  558. }
  559.  
  560. function checkRule(r){
  561. let urlReg=new RegExp(r.url, "i");
  562. if(urlReg.test(location.href)){
  563. if(r.wait){
  564. let waitTime=500,checkEval;
  565. if(isNaN(r.wait)){
  566. try{
  567. checkEval=Function("doc",'"use strict";' + r.wait);
  568. }catch(e){
  569. debug(e);
  570. }
  571. }else{
  572. waitTime=r.wait;
  573. }
  574. let checkReady=()=>{
  575. setTimeout(()=>{
  576. if(!ruleMatch(r) || (checkEval && !checkEval(document))){
  577. checkReady();
  578. }else{
  579. setRule(r);
  580. }
  581. },parseInt(waitTime));
  582. };
  583. checkReady();
  584. return true;
  585. }
  586. if(r.pinUrl){
  587. setRule(r);
  588. return true;
  589. }
  590. if(!ruleMatch(r)){
  591. return false;
  592. }
  593. setRule(r);
  594. return true;
  595. }
  596. return false;
  597. }
  598.  
  599. for(let i in this.hpRules){
  600. let rule=this.hpRules[i];
  601. if(!rule || !rule.url)continue;
  602. if(rule.singleUrl){
  603. if(location.origin+location.pathname==rule.url){
  604. setRule(rule);
  605. return;
  606. }
  607. continue;
  608. }
  609. if(checkRule(rule))return;
  610. }
  611. for(let i in this.customRules){
  612. let rule=this.customRules[i];
  613. if(!rule || !rule.url)continue;
  614. if(checkRule(rule))return;
  615. }
  616. let r=0;
  617. function searchByTime(){
  618. setTimeout(()=>{
  619. let end=r+80;
  620. end=end>self.rules.length?self.rules.length:end;
  621. for(;r<end;r++){
  622. let rule=self.rules[r];
  623. if(checkRule(rule))return;
  624. }
  625. if(end>=self.rules.length){
  626. self.curSiteRule={};
  627. self.curSiteRule.url=location.origin+location.pathname;
  628. self.curSiteRule.singleUrl=true;
  629. callback();
  630. return;
  631. }else{
  632. searchByTime();
  633. }
  634. },20);
  635. }
  636. searchByTime();
  637. }
  638.  
  639. geneSelector(ele){
  640. let selector=ele.tagName;
  641. //Google id class都是隨機。百度更過分,style script順序都是隨機的
  642. //if(ele.id) selector += '#' + ele.id;
  643. //if(ele.classList) selector += [].map.call(ele.classList,d=>'.'+d).join('');
  644. let parent = ele.parentElement;
  645. if(parent){
  646. let i,j=0;
  647. for(i=0;i<parent.children.length;i++){
  648. if(parent.children[i].tagName==selector){
  649. j++;
  650. if(parent.children[i]==ele){
  651. break;
  652. }
  653. }
  654. }
  655. selector = this.geneSelector(parent) + ' > ' + selector + (parent.tagName=="HTML"?"":`:nth-of-type(${j})`);
  656. }
  657. return selector;
  658. }
  659.  
  660. getPageElement(doc, curWin, dontFind) {
  661. let pageElement=null;
  662. let self=this;
  663. if(this.curSiteRule.pageElement){
  664. pageElement=this.curSiteRule.type==0?getAllElementsByXpath(this.curSiteRule.pageElement,doc,doc):doc.querySelectorAll(this.curSiteRule.pageElement);
  665. }
  666. if((!pageElement || pageElement.length==0) && curWin && !dontFind){
  667. let body=doc.body;
  668. if(!body)return null;
  669. let bodyHeight=parseInt(body.scrollHeight);
  670. let curHeight=bodyHeight;
  671. function checkElement(ele){
  672. if(curHeight/bodyHeight<=0.30){
  673. self.curSiteRule.pageElement=allOfBody;
  674. debug(self.curSiteRule.pageElement);
  675. return [body];
  676. }
  677. if(ele.tagName=="TBODY" || ele.tagName=="UL"){
  678. self.curSiteRule.pageElement=self.geneSelector(ele)+">*";
  679. if(ele.children.length>0 && ele.children[0].querySelector("th")){
  680. self.curSiteRule.pageElement+=":not(:first-child)";
  681. }
  682. debug(self.curSiteRule.pageElement);
  683. return ele.children;
  684. }
  685. if(ele.children.length==0 && !self.curSiteRule.pageElement){
  686. if(ele.parentNode.tagName=="P")ele=ele.parentNode;
  687. self.curSiteRule.pageElement=self.geneSelector(ele.parentNode)+">"+ele.tagName;
  688. debug(self.curSiteRule.pageElement);
  689. return [ele];
  690. }
  691. let i,maxHeight=curHeight*0.6,curMaxEle=null,curMaxArea=0,maxWidth=0;
  692. let isHori=true;
  693. let offsetTop=ele.children[0].offsetTop;
  694. for(i=0;i<ele.children.length;i++){
  695. if(ele.children[i].offsetTop!=offsetTop){
  696. isHori=false;
  697. break;
  698. }
  699. }
  700. for(i=0;i<ele.children.length;i++){
  701. let curNode=ele.children[i];
  702. if(curNode.tagName=="CANVAS")continue;
  703. let comStyle=curWin.getComputedStyle(curNode);
  704. let h=parseInt(curNode.scrollHeight);
  705. let w=parseInt(curNode.scrollWidth);
  706. if(isNaN(h) || isNaN(w))continue;
  707. if(isHori && h==0)continue;
  708. let a=h*w+h,moreChild=curNode.children[0];
  709. while(moreChild){
  710. comStyle=curWin.getComputedStyle(moreChild);
  711. let ch=parseInt(moreChild.scrollHeight);
  712. let cw=parseInt(moreChild.scrollWidth);
  713. if(h<ch)h=ch;
  714. if(moreChild.innerText!="" && !isNaN(ch) && !isNaN(cw)){
  715. a+=ch*cw;
  716. }
  717. moreChild=moreChild.nextElementSibling;
  718. }
  719. let isMax=false;
  720. if(isHori){
  721. if(maxWidth<w){
  722. isMax=true;
  723. }else if(maxWidth==w && curMaxArea<a){
  724. isMax=true;
  725. }
  726. }else{
  727. isMax=curMaxArea<a;
  728. }
  729. if(curMaxEle==null || isMax){
  730. if(h>0)curHeight=h;
  731. curMaxArea=a;
  732. maxWidth=w;
  733. curMaxEle=curNode;
  734. }
  735. }
  736. if(curMaxEle && (isHori || curHeight>maxHeight)){
  737. return checkElement(curMaxEle);
  738. }
  739. if(!self.curSiteRule.pageElement){
  740. if(ele.tagName=="P" || ele.tagName=="BR")ele=ele.parentNode;
  741. self.curSiteRule.pageElement=self.geneSelector(ele);
  742. if(ele.children.length>1 && ele.tagName!="UL")self.curSiteRule.pageElement+=">*";
  743. debug(self.curSiteRule.pageElement);
  744. }
  745. return (ele.tagName=="UL"||ele.children.length==1)?[ele]:ele.children;
  746. }
  747. pageElement=checkElement(body);
  748. if(pageElement)this.saveCurSiteRule();
  749. }
  750. if(this.insert && pageElement && pageElement[0]){
  751. let example=this.insertPos==2?this.insert.children[0]:this.insert;
  752. let inTable=example.parentNode.tagName=="TABLE" ||
  753. example.tagName=="TR" ||
  754. example.tagName=="TBODY" ||
  755. (example.previousElementSibling && example.previousElementSibling.tagName=="TR") ||
  756. (example.previousElementSibling && example.previousElementSibling.tagName=="TBODY");
  757. if(inTable && pageElement[0].tagName!="TR" && pageElement[0].tagName!="TBODY"){
  758. pageElement=null;
  759. }
  760. }
  761. return pageElement;
  762. }
  763.  
  764. getPage(doc){
  765. if(_unsafeWindow.Discourse)return {};
  766. let canSave=false;//發現頁碼選擇器在其他頁對不上,還是別保存了
  767. let url=this.curUrl.replace("#!","").replace("index.php?","?");
  768. let pageNum=1,preStr="",afterStr="";
  769. let pageMatch1=url.match(/(.*[a-z\/\-_](?:p|page)?\/?)(\d+)(\.s?html?$|\/?$)/i);
  770. let pageMatch2=url.match(/(.*[\?&]p(?:age)?=)(\d+)($|[#&].*)/i);
  771. if(pageMatch1){
  772. preStr=pageMatch1[1];
  773. pageNum=pageMatch1[2];
  774. afterStr=pageMatch1[3];
  775. }else if(pageMatch2){
  776. preStr=pageMatch2[1];
  777. pageNum=pageMatch2[2];
  778. afterStr=pageMatch2[3];
  779. }
  780. let curPage=doc,i,cur,jsNext;
  781. let next=curPage.querySelector(".page-next>a")||
  782. curPage.querySelector("a.next_page")||
  783. curPage.querySelector("#next_page")||
  784. curPage.querySelector(".nextPage")||
  785. curPage.querySelector("a[data-pagination=next]")||
  786. curPage.querySelector(".pagination a[rel=next]")||
  787. curPage.querySelector("a.pageright")||
  788. curPage.querySelector("a#rightFix")||
  789. curPage.querySelector("a.next")||
  790. curPage.querySelector("a#next")||
  791. curPage.querySelector(".next>a")||
  792. curPage.querySelector(".next>button")||
  793. curPage.querySelector("a[alt=next]")||
  794. curPage.querySelector("[title=next]");
  795. if(next && (!next.href || /^javascript:/.test(next.href))){
  796. jsNext=next;
  797. next=null;
  798. }
  799. if(!next){
  800. next=curPage.querySelectorAll("[aria-label='Next']");
  801. if(next && next.length==1){
  802. next=next[0];
  803. if(!next.href || /^javascript:/.test(next.href)){
  804. jsNext=next;
  805. next=null;
  806. }
  807. }else{
  808. next=null;
  809. }
  810. }
  811. if(!next){
  812. next=curPage.querySelectorAll("[aria-label='Next page']");
  813. if(next && next.length==1){
  814. next=next[0];
  815. if(!next.href || /^javascript:/.test(next.href)){
  816. jsNext=next;
  817. next=null;
  818. }
  819. }else{
  820. next=null;
  821. }
  822. }
  823. if(!next){
  824. let pageDiv=curPage.querySelector("div.wp-pagenavi");
  825. if(pageDiv){
  826. cur=pageDiv.querySelector("span.current");
  827. if(cur){
  828. next=cur.nextSibling;
  829. }
  830. }else{
  831. cur=curPage.querySelector("div.article-paging>span");
  832. if(cur){
  833. next=cur.nextElementSibling;
  834. }
  835. }
  836. }
  837. if(!next){
  838. let pageDiv=curPage.querySelector("div.pages>ul");
  839. if(pageDiv){
  840. cur=pageDiv.querySelector("li>b");
  841. if(cur)next=cur.parentNode.nextElementSibling.querySelector("a");
  842. }
  843. }
  844. if(!next){
  845. let aTags=curPage.querySelectorAll("a");
  846. let next1,next2,next3,next4,nextJs1,nextJs2,nextJs3;
  847. for(i=aTags.length-1;i>=0;i--){
  848. let aTag=aTags[i];
  849. if(aTag.innerText=="§")continue;
  850. if(aTag.style.display=="none")continue;
  851. if(next1 && next2 && next3 && next4)break;
  852. if(!next1){
  853. if(/^\s*[下后後][一1]?[页頁张張]|^next( page)?\s*›?$|次のページ/i.test(aTag.innerText)){
  854. if(aTag.innerText.length>15)continue;
  855. if(!aTag.href || /^javascript:/.test(aTag.href)){
  856. if(!nextJs1)nextJs1=aTag;
  857. }else{
  858. next1=aTag;
  859. }
  860. }
  861. }
  862. if(!next2){
  863. if(/^\s*[下后後][一1]?[章话話]/i.test(aTag.innerText)){
  864. if(!aTag.href || /^javascript:/.test(aTag.href)){
  865. if(!nextJs2)nextJs2=aTag;
  866. }else{
  867. next2=aTag;
  868. }
  869. }
  870. }
  871. if(!next3){
  872. if(aTag.innerText=="&gt;" || aTag.innerText=="▶" || aTag.innerText==">" || aTag.innerText=="›" || /nextpage/i.test(aTag.className)){
  873. if(!aTag.href || /^javascript:/.test(aTag.href)){
  874. if(!nextJs3)nextJs3=aTag;
  875. }else{
  876. next3=aTag;
  877. }
  878. }
  879. }
  880. if(!aTag.href || /^javascript:/.test(aTag.href))continue;
  881. if(!next4){
  882. if(aTag.href.replace("?&","?").replace("#!","").replace("index.php?","?").replace(preStr,"").replace(afterStr,"")==parseInt(pageNum)+1){
  883. next4=aTag;
  884. }else if(this.curUrl!=aTag.href && aTag.href.replace("?&","?").replace("index.php?","?").indexOf(url)!=-1 && /^[\/\?&]?[_-]?(p|page)?=?\/?2(\/|\?|&|$)/i.test(aTag.href.replace(url,"").replace(/\.s?html?$/i,""))){
  885. let curHref=aTag.getAttribute("href");
  886. let pageOne=curHref.replace(/\/2(\/|\?|&|$)/,"/1$1");
  887. if(pageOne==curHref)pageOne=null;
  888. else pageOne=curPage.querySelector(`a[href='${pageOne}']`);
  889. if(!pageOne)next4=aTag;
  890. }
  891. }
  892. }
  893. next=next1||next3||next4||next2||nextJs1||nextJs3||nextJs2;
  894. }
  895. if(!next)next=jsNext;
  896. if(next && next.classList.contains("results-more"))next=null;
  897. return {next:next,canSave:canSave};
  898. }
  899.  
  900. canonicalUri(src, base_path) {
  901. if(src.charAt(0)=="#")return location.href+src;
  902. var root_page = /^[^?#]*\//.exec(location.href)[0],
  903. root_domain = /^\w+\:\/\/\/?[^\/]+/.exec(root_page)[0],
  904. absolute_regex = /^\w+\:\/\//;
  905. src=src.replace(/\.\//,"");
  906. if (/^\/\/\/?/.test(src)){
  907. src = location.protocol + src;
  908. }
  909. else if (!absolute_regex.test(src) && src.charAt(0) != "/"){
  910. src = (base_path || "") + src;
  911. }
  912. return (absolute_regex.test(src) ? src : ((src.charAt(0) == "/" ? root_domain : root_page) + src));
  913. }
  914.  
  915. getLinkByPage(url, pageNum) {
  916. if(!url)return;
  917. if(this.curSiteRule.pageNum){
  918. let result=this.curSiteRule.pageNum;
  919. let strMatch=result.match(/\{.*?}/);
  920. if(!strMatch)return null;
  921. let urlReg=new RegExp("("+result.replace(strMatch[0], ")\\d+(")+")");
  922. let code=strMatch[0].replace(/^{/,"").replace(/}$/,"").replace(/\$p/g,pageNum);
  923. if(code==pageNum){
  924. result=url.replace(urlReg,"$1"+code+"$2");
  925. }else{
  926. try{
  927. code=Function('"use strict";return ' + code)();
  928. result=url.replace(urlReg,"$1"+code+"$2");
  929. }catch(e){
  930. debug(e);
  931. }
  932. }
  933. return result==url?url.replace(/([&\/\?](p=|page[=\/]))\d+/i, "$1"+pageNum):result;
  934. }else{
  935. return url.replace(/([&\/\?](p=|page[=\/]))\d+/i, "$1"+pageNum);
  936. }
  937. }
  938.  
  939. getNextLink(doc) {
  940. let nextLink=null,page;
  941. if(this.curSiteRule.pageElementByJs){
  942. this.nextLinkHref="#";
  943. return true;
  944. }else if(this.curSiteRule.nextLinkByJs){
  945. try{
  946. let targetUrl=Function("doc",'"use strict";' + this.curSiteRule.nextLinkByJs)(doc);
  947. if(targetUrl)nextLink={href:targetUrl};
  948. }catch(e){
  949. debug(e);
  950. }
  951. }else if(this.curSiteRule.nextLinkByUrl){
  952. let targetUrl=this.curUrl.replace(new RegExp(this.curSiteRule.nextLinkByUrl[0]), this.curSiteRule.nextLinkByUrl[1]);
  953. if(targetUrl != this.curUrl){
  954. let reps=targetUrl.match(/{.*?}/g);
  955. if(reps){
  956. reps.forEach(rep=>{
  957. let code=rep.replace("{","").replace("}","");
  958. let result=code.match(/^(\d+)\+1$/);
  959. if(result){
  960. result=parseInt(result[1])+1;
  961. }else{
  962. try{
  963. result=Function('"use strict";return ' + code)();
  964. }catch(e){
  965. debug(e);
  966. }
  967. }
  968. targetUrl=targetUrl.replace(rep, result);
  969. });
  970. }
  971. }
  972. nextLink={href:targetUrl};
  973. }else if(this.curSiteRule.nextLink){
  974. if(this.curSiteRule.nextLink!="0"){
  975. nextLink=this.curSiteRule.type==0?getElementByXpath(this.curSiteRule.nextLink,doc,doc):doc.querySelector(this.curSiteRule.nextLink);
  976. }
  977. }else{
  978. page=this.getPage(doc);
  979. nextLink=page.next;
  980. if(nextLink){
  981. if(nextLink.tagName=="INPUT" && nextLink.parentNode.tagName=="FORM"){
  982. let params=[];
  983. let form=nextLink.parentNode;
  984. [].forEach.call(form.querySelectorAll("input"), input=>{
  985. params.push(input.name+'='+input.value);
  986. });
  987. nextLink.href=form.action+'?'+params.join('&');
  988. }
  989. if(nextLink.classList.contains("noClick")){
  990. this.nextLinkHref=false;
  991. return null;
  992. }else if(doc==document){
  993. if((!nextLink.href || /^javascript:/.test(nextLink.href)) && !isVisible(nextLink, _unsafeWindow)){
  994. this.nextLinkHref=false;
  995. return null;
  996. }else{
  997. let nextLinkCs=_unsafeWindow.getComputedStyle(nextLink);
  998. if(nextLinkCs.cursor=="not-allowed"){
  999. this.nextLinkHref=false;
  1000. return null;
  1001. }
  1002. }
  1003. }
  1004. }
  1005. }
  1006. if(nextLink){
  1007. if(nextLink.href && nextLink.href==this.curUrl){
  1008. nextLink=null;
  1009. }else if(/^javascript:/.test(nextLink.href) && (this.curSiteRule.action==0 || this.curSiteRule.action==1)){
  1010. nextLink=null;
  1011. }
  1012. /*if(!this.curSiteRule.nextLink && page && page.canSave){
  1013. this.curSiteRule.nextLink=this.geneSelector(nextLink);
  1014. this.curSiteRule.type=1;
  1015. this.saveCurSiteRule();
  1016. }*/
  1017. }
  1018. if(nextLink){
  1019. this.nextLinkHref=(nextLink.href && !/^javascript:/.test(nextLink.href))?this.canonicalUri(nextLink.href):"#";
  1020. debug(nextLink);
  1021. }else{
  1022. this.nextLinkHref=false;
  1023. }
  1024. return nextLink;
  1025. }
  1026.  
  1027. getInsert(refresh) {
  1028. if(refresh){
  1029. this.insert=null;
  1030. }
  1031. if(this.insert && !refresh){
  1032. let parent=this.insert;
  1033. while(parent && parent.nodeName!="BODY"){
  1034. parent=parent.parentNode;
  1035. }
  1036. if(parent && parent.nodeName=="BODY"){
  1037. return this.insert;
  1038. }
  1039. }
  1040. if(this.curSiteRule.insert){
  1041. this.insert=this.curSiteRule.type==0?getElementByXpath(this.curSiteRule.insert,document):document.querySelector(this.curSiteRule.insert);
  1042. }else{
  1043. let pageElement=this.getPageElement(document, _unsafeWindow);
  1044. if(pageElement && pageElement.length>0){
  1045. var pELast = pageElement[pageElement.length - 1];
  1046. this.insert = pELast.nextSibling ? pELast.nextSibling : pELast.parentNode.appendChild(document.createTextNode(' '));
  1047. }
  1048. }
  1049. return this.insert;
  1050. }
  1051.  
  1052. pageInit(doc,eles){
  1053. let code=this.curSiteRule.pageInit;
  1054. if(code){
  1055. try{
  1056. Function("doc","eles",'"use strict";' + code)(doc,eles);
  1057. }catch(e){
  1058. debug(e);
  1059. }
  1060. }
  1061. }
  1062.  
  1063. pageAction(doc,eles){
  1064. let code=this.curSiteRule.pageAction;
  1065. if(code){
  1066. try{
  1067. Function("doc","eles",'"use strict";' + code)(doc,eles);
  1068. }catch(e){
  1069. debug(e);
  1070. }
  1071. }
  1072. let setLazyImg=img=>{
  1073. let realSrc;
  1074. if(img.getAttribute("_src") && !img.src){
  1075. realSrc=img.getAttribute("_src");
  1076. }else if(img.dataset && img.dataset.original){
  1077. realSrc=img.dataset.original;
  1078. }else if(img.dataset && img.dataset.src){
  1079. realSrc=img.dataset.src;
  1080. }else if(img._lazyrias && img._lazyrias.srcset){
  1081. realSrc=img._lazyrias.srcset[img._lazyrias.srcset.length-1];
  1082. }else if(img.dataset && img.dataset.origFile){
  1083. realSrc=img.dataset.origFile;
  1084. }else if(img.srcset){
  1085. var srcs=img.srcset.split(","),largeSize=0;
  1086. srcs.forEach(srci=>{
  1087. let srcInfo=srci.trim().split(" "),curSize=parseInt(srcInfo[1]);
  1088. if(srcInfo[1] && curSize>largeSize){
  1089. largeSize=curSize;
  1090. realSrc=srcInfo[0];
  1091. }
  1092. });
  1093. }
  1094. if(realSrc){
  1095. img.src=realSrc;
  1096. img.style.display="block";
  1097. }
  1098. };
  1099. [].forEach.call(eles, ele=>{
  1100. if(ele.tagName=="IMG"){
  1101. setLazyImg(ele);
  1102. }else{
  1103. [].forEach.call(ele.querySelectorAll("img"), img=>{
  1104. setLazyImg(img);
  1105. });
  1106. }
  1107. if(ele.tagName=="A" && ele.classList.contains("lazyload")){
  1108. if(ele.dataset.original){
  1109. ele.style.backgroundImage='url("'+ele.dataset.original+'")';
  1110. }
  1111. }else{
  1112. [].forEach.call(ele.querySelectorAll("a.lazyload"), a=>{
  1113. if(a.dataset.original){
  1114. a.style.backgroundImage='url("'+a.dataset.original+'")';
  1115. }
  1116. });
  1117. }
  1118. });
  1119. let lazyImgSrc=this.curSiteRule.lazyImgSrc;
  1120. if(lazyImgSrc){
  1121. [].forEach.call(eles, ele=>{
  1122. [].forEach.call(ele.querySelectorAll("img"), img=>{
  1123. if(img.getAttribute(lazyImgSrc)){
  1124. img.src=img.getAttribute(lazyImgSrc);
  1125. }
  1126. });
  1127. });
  1128. }
  1129. }
  1130.  
  1131. initPage(callback){
  1132. let self=this;
  1133. curPage=1;
  1134. //if(this.curSiteRule.url && !this.curSiteRule.singleUrl)return;
  1135. this.curSiteRule={};
  1136. this.pageDoc=document;
  1137. this.nextLinkHref=null;
  1138. this.curUrl=location.href;
  1139. this.getRule(()=>{
  1140. if(self.curSiteRule.enable==0){
  1141. debug("Stop as rule disable");
  1142. isPause=true;
  1143. return;
  1144. }
  1145. if(self.curSiteRule && !self.curSiteRule.singleUrl){
  1146. self.hpRules=self.hpRules.filter(item=>{return item&&item.url!=self.curSiteRule.url});
  1147. self.hpRules.unshift(self.curSiteRule);
  1148. if(self.hpRules.length>30){
  1149. self.hpRules.pop();
  1150. }
  1151. storage.setItem("hpRules", self.hpRules);
  1152. }
  1153. let css=self.curSiteRule.css;
  1154. if(css){
  1155. _GM_addStyle(css);
  1156. }
  1157. let code=self.curSiteRule.init;
  1158. if(code){
  1159. try{
  1160. Function('doc','"use strict";' + code)(null);
  1161. }catch(e){
  1162. debug(e);
  1163. }
  1164. }
  1165. self.getNextLink(document);
  1166. callback();
  1167. });
  1168. }
  1169.  
  1170. insertPage(doc, eles, url, callback, tried){
  1171. let oldUrl=this.curUrl;
  1172. let oldTitle=this.pageDoc.title;
  1173. this.pageDoc=doc;
  1174. this.curUrl=url;
  1175. let nextLink=this.getNextLink(doc);
  1176. if(curPage==1 && !tried && !this.nextLinkHref && this.curSiteRule.singleUrl && this.curSiteRule.pageElement && this.curSiteRule.pageElement!=allOfBody){
  1177. this.curSiteRule.action=1;
  1178. this.curUrl=location.href;
  1179. return false;
  1180. }
  1181. if(callback)callback(eles);
  1182. this.getInsert();
  1183. var self=this,newEles=[];
  1184. if(!eles || eles.length==0 || !self.insert || !self.insert.parentNode){
  1185. }else{
  1186. this.pageInit(doc, eles);
  1187. [].forEach.call(eles, ele=>{
  1188. let newEle=ele.cloneNode(true);
  1189. let oldCanvass=ele.querySelectorAll("canvas");
  1190. let newCanvass=newEle.querySelectorAll("canvas");
  1191. for(let i=0;i<oldCanvass.length;i++){
  1192. let oldCanvas=oldCanvass[i];
  1193. let newCanvas=newCanvass[i];
  1194. newCanvas.getContext('2d').drawImage(oldCanvas, 0, 0);
  1195. }
  1196. if(self.curSiteRule.insertPos==2){
  1197. self.insert.appendChild(newEle);
  1198. }else{
  1199. self.insert.parentNode.insertBefore(newEle, self.insert);
  1200. }
  1201. newEles.push(newEle);
  1202. });
  1203. }
  1204. this.pageAction(doc, newEles);
  1205. if(oldUrl!=location.href){
  1206. let isJs=/^(javascript|#)/.test(oldUrl.replace(location.href,""));
  1207. if(rulesData.enableHistory && !isJs){
  1208. _unsafeWindow.history.replaceState(undefined, oldTitle, oldUrl);
  1209. document.title=oldTitle;
  1210. }
  1211. }
  1212. return true;
  1213. }
  1214. }
  1215. var ruleParser = new RuleParser();
  1216.  
  1217. function initConfig(){
  1218. _GM_registerMenuCommand(i18n(forceState==1?"enable":"disableSite"), ()=>{
  1219. storage.setItem("forceState_"+location.host, (forceState==1?0:1));
  1220. location.reload();
  1221. });
  1222. _GM_registerMenuCommand(i18n("update"), ()=>{
  1223. updateRules(()=>{
  1224. alert(i18n("updateSucc"));
  1225. location.reload();
  1226. },(rule,err)=>{
  1227. alert("Update "+rule.url+" rules fail!");
  1228. });
  1229. alert(i18n("beginUpdate"));
  1230. });
  1231.  
  1232. var configCon,insertPos;
  1233. if(location.href==configPage){
  1234. _GM_addStyle(`
  1235. p>span:nth-child(1),p>span:nth-child(2),p>span:nth-child(3){
  1236. cursor: pointer;
  1237. user-select: none;
  1238. }
  1239. p>span:nth-child(1):hover,p>span:nth-child(2):hover,p>span:nth-child(3):hover{
  1240. color:red;
  1241. }
  1242. .updateDate{
  1243. cursor: pointer;
  1244. user-select: none;
  1245. }
  1246. .updateDate:hover{
  1247. color:red;
  1248. }
  1249. `);
  1250. configCon=document.querySelector(".markdown-body");
  1251. insertPos=configCon.querySelector("hr");
  1252. }else if(location.href==configPage){
  1253. }else return false;
  1254. class Rulebar {
  1255. init(ruleUrl){
  1256. this.ruleUrl=ruleUrl;
  1257. this.item=document.createElement("p");
  1258. this.item.title=ruleUrl.type==0?"AutoPagerize Rules":"Pagetual Rules";
  1259. this.item.dataset.id=this.ruleUrl.id;
  1260. let url=document.createElement("span");
  1261. url.innerHTML=ruleUrl.url;
  1262. let up=document.createElement("span");
  1263. up.innerHTML="↑ ";
  1264. up.title=i18n("sortTitle");
  1265. let down=document.createElement("span");
  1266. down.innerHTML="↓ ";
  1267. down.title=i18n("sortTitle");
  1268. let del=document.createElement("span");
  1269. del.innerHTML="× ";
  1270. up.onclick=e=>{
  1271. this.moveUp();
  1272. };
  1273. down.onclick=e=>{
  1274. this.moveDown();
  1275. };
  1276. del.onclick=e=>{
  1277. this.del();
  1278. };
  1279. this.item.appendChild(up);
  1280. this.item.appendChild(down);
  1281. this.item.appendChild(del);
  1282. this.item.appendChild(url);
  1283. configCon.insertBefore(this.item, insertPos);
  1284. }
  1285. saveSort(){
  1286. let sort=[];
  1287. [].forEach.call(this.item.parentNode.querySelectorAll("p[data-id]"), i=>{
  1288. sort.push(i.dataset.id);
  1289. });
  1290. rulesData.sort=sort;
  1291. storage.setItem("rulesData", rulesData);
  1292. }
  1293. moveUp(){
  1294. let preE=this.item.previousElementSibling;
  1295. if(preE.tagName=="P" && preE.children.length>1){
  1296. this.item.parentNode.insertBefore(this.item,preE);
  1297. this.saveSort();
  1298. }
  1299. }
  1300. moveDown(){
  1301. let nextE=this.item.nextElementSibling;
  1302. if(nextE.tagName=="P" && nextE.children.length>1){
  1303. this.item.parentNode.insertBefore(nextE,this.item);
  1304. this.saveSort();
  1305. }
  1306. }
  1307. del(){
  1308. if(this.ruleUrl.id<2){
  1309. alert(i18n("cantDel"));
  1310. }else if(window.confirm(i18n("confirmDel"))){
  1311. for(let u=0;u<rulesData.urls.length;u++){
  1312. if(this.ruleUrl.id==rulesData.urls[u].id){
  1313. rulesData.urls.splice(u,1);
  1314. break;
  1315. }
  1316. }
  1317. for(let u=0;u<rulesData.sort.length;u++){
  1318. if(this.ruleUrl.id==rulesData.sort[u]){
  1319. rulesData.sort.splice(u,1);
  1320. break;
  1321. }
  1322. }
  1323. storage.setItem("rulesData", rulesData);
  1324. ruleParser.rules=ruleParser.rules.filter(item=>{return item.from!=this.ruleUrl.id});
  1325. storage.setItem("rules", ruleParser.rules);
  1326. this.item.parentNode.removeChild(this.item);
  1327. //location.reload();
  1328. }
  1329. }
  1330. }
  1331. let updateP=document.createElement("p"),i=0;
  1332. let now=new Date().getTime(),inUpdate=false;
  1333.  
  1334.  
  1335. let pastDate=(new Date(updateDate)).toString(),passStr;
  1336. let passTime=(now-updateDate)/1000;
  1337. if(isNaN(passTime)){
  1338. passStr=i18n("firstUpdate");
  1339. }else if(passTime<60){
  1340. passStr=i18n("passSec", parseInt(passTime))+" ← "+i18n("click2update");
  1341. }else if(passTime<60*60){
  1342. passStr=i18n("passMin", parseInt(passTime/60))+" ← "+i18n("click2update");
  1343. }else if(passTime<60*60*24){
  1344. passStr=i18n("passHour", parseInt(passTime/3600))+" ← "+i18n("click2update");
  1345. }else{
  1346. passStr=i18n("passDay", parseInt(passTime/86400))+" ← "+i18n("click2update");
  1347. }
  1348.  
  1349.  
  1350. updateP.className="updateDate";
  1351. updateP.innerHTML=passStr;
  1352. updateP.title=i18n("update")+" - "+pastDate;
  1353. updateP.onclick=e=>{
  1354. updateRules(()=>{
  1355. alert(i18n("updateSucc"));
  1356. updateP.innerHTML=i18n("passSec", 0);
  1357. updateP.title=i18n("update");
  1358. },(rule,err)=>{
  1359. alert("Update "+rule.url+" rules fail!");
  1360. });
  1361. alert(i18n("beginUpdate"));
  1362. };
  1363. configCon.insertBefore(updateP, insertPos);
  1364. if(ruleUrls){
  1365. ruleUrls.forEach(ruleUrl=>{
  1366. var rulebar=new Rulebar();
  1367. rulebar.init(ruleUrl);
  1368. });
  1369. }
  1370. let customUrlsTitle=document.createElement("h2");
  1371. customUrlsTitle.innerHTML=i18n("customUrls");
  1372. configCon.insertBefore(customUrlsTitle, insertPos);
  1373. let customUrlsInput=document.createElement("textarea");
  1374. customUrlsInput.style.width="100%";
  1375. customUrlsInput.placeholder="0|http://wedata.net/databases/AutoPagerize/items_all.json";
  1376. configCon.insertBefore(customUrlsInput, insertPos);
  1377.  
  1378. let opacityTitle=document.createElement("h2");
  1379. opacityTitle.innerHTML=i18n("opacity");
  1380. let opacityInput=document.createElement("input");
  1381. opacityInput.value=rulesData.opacity*100;
  1382. opacityInput.type="number";
  1383. opacityInput.style.width="50px";
  1384. opacityInput.style.margin="0 0 0 10px";
  1385. opacityTitle.appendChild(opacityInput);
  1386. configCon.insertBefore(opacityTitle, insertPos);
  1387.  
  1388. function createCheckbox(innerText, val){
  1389. let title=document.createElement("h2");
  1390. title.innerHTML=innerText;
  1391. let input=document.createElement("input");
  1392. input.type="checkbox";
  1393. input.style.width="50px";
  1394. input.style.height="20px";
  1395. input.checked=val;
  1396. title.appendChild(input);
  1397. configCon.insertBefore(title, insertPos);
  1398. return input;
  1399. }
  1400.  
  1401. let hideBarInput=createCheckbox(i18n("hideBar"), rulesData.hideBar);
  1402. let dbClick2StopInput=createCheckbox(i18n("dbClick2Stop"), rulesData.dbClick2Stop);
  1403. let enableWhiteListInput=createCheckbox(i18n("autoRun"), rulesData.enableWhiteList!=true);
  1404. let enableDebugInput=createCheckbox(i18n("enableDebug"), rulesData.enableDebug!=false);
  1405. let enableHistoryInput=createCheckbox(i18n("enableHistory"), rulesData.enableHistory!=false);
  1406.  
  1407. let customRulesTitle=document.createElement("h2");
  1408. customRulesTitle.innerHTML=i18n("customRules")
  1409. configCon.insertBefore(customRulesTitle, insertPos);
  1410. let customRulesInput=document.createElement("textarea");
  1411. customRulesInput.style.width="100%";
  1412. customRulesInput.style.height="500px";
  1413. 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]`;
  1414. customRulesInput.value=getFormatJSON(ruleParser.customRules);
  1415. configCon.insertBefore(customRulesInput, insertPos);
  1416. let saveBtn=document.createElement("button");
  1417. saveBtn.innerHTML=i18n("save");
  1418. saveBtn.style.width="100%";
  1419. configCon.insertBefore(saveBtn, insertPos);
  1420. saveBtn.onclick=e=>{
  1421. try{
  1422. storage.setItem("hpRules", []);
  1423. if(customRulesInput.value==""){
  1424. storage.setItem("customRules", "");
  1425. }else{
  1426. let customRules=JSON.parse(customRulesInput.value);
  1427. if(Array && Array.isArray && !Array.isArray(customRules)){
  1428. alert("Rules must be a Array!");
  1429. return;
  1430. }
  1431. debug(customRules);
  1432. storage.setItem("customRules", customRules);
  1433. }
  1434. }catch(e){
  1435. debug(e);
  1436. alert("JSON error, check again!");
  1437. return;
  1438. }
  1439. rulesData.opacity=opacityInput.value/100;
  1440. rulesData.hideBar=hideBarInput.checked;
  1441. rulesData.dbClick2Stop=dbClick2StopInput.checked;
  1442. rulesData.enableWhiteList=!enableWhiteListInput.checked;
  1443. rulesData.enableDebug=enableDebugInput.checked;
  1444. rulesData.enableHistory=enableHistoryInput.checked;
  1445. storage.setItem("rulesData", rulesData);
  1446. let customUrls=customUrlsInput.value.trim();
  1447. if(customUrls){
  1448. customUrls=customUrls.split(/\n/);
  1449. for(let c=0;c<customUrls.length;c++){
  1450. let urlArr=customUrls[c].split("|"),url,type=1;
  1451. if(urlArr.length==1){
  1452. url=urlArr[0].trim();
  1453. if(!/^http/.test(url)){
  1454. alert("Wrong url, check again!");
  1455. return;
  1456. }
  1457. }else if(urlArr.length==2){
  1458. type=urlArr[0].trim();
  1459. url=urlArr[1].trim();
  1460. if(!/^http/.test(url)){
  1461. alert("Wrong url, check again!");
  1462. return;
  1463. }
  1464. }else{
  1465. break;
  1466. }
  1467. let maxId=0,hasUrl=false;
  1468. if(!rulesData.urls){
  1469. rulesData.urls=[];
  1470. maxId=1;
  1471. }else{
  1472. rulesData.urls.forEach(u=>{
  1473. if(maxId<u.id){
  1474. maxId=u.id;
  1475. }
  1476. if(u.url==url){
  1477. hasUrl=true;
  1478. }
  1479. });
  1480. if(hasUrl)break;
  1481. }
  1482. rulesData.urls.push({id:maxId+1,url:url,type:type});
  1483. rulesData.sort.push(maxId+1);
  1484. storage.setItem("rulesData", rulesData);
  1485. }
  1486. }
  1487. alert("Modified successfully");
  1488. location.reload();
  1489. };
  1490. return true;
  1491. }
  1492.  
  1493. var inUpdate=false;
  1494. function updateRules(success,fail){
  1495. if(inUpdate)return;
  1496. inUpdate=true;
  1497. let ruleIndex=ruleUrls.length-1;
  1498. storage.setItem("hpRules", []);
  1499. function addNextRule(){
  1500. if(ruleIndex<0){
  1501. let now=new Date().getTime();
  1502. storage.setItem("ruleLastUpdate", now);
  1503. storage.setItem("rules", ruleParser.rules);
  1504. inUpdate=false;
  1505. success();
  1506. }else{
  1507. let rule=ruleUrls[ruleIndex--];
  1508. ruleParser.addRuleByUrl(rule.url, rule.type, rule.id, (json,err)=>{
  1509. if(!json){
  1510. fail(rule,err);
  1511. }
  1512. storage.setItem("rules", ruleParser.rules);
  1513. addNextRule();
  1514. })
  1515. }
  1516. }
  1517. addNextRule();
  1518. }
  1519.  
  1520. function objIsArr(obj) {
  1521. return obj &&
  1522. typeof obj === 'object' &&
  1523. typeof obj.length === 'number' &&
  1524. !(obj.propertyIsEnumerable('length'));
  1525. }
  1526.  
  1527. function isVisible(el, win) {
  1528. if(!el.offsetParent)return false;
  1529. var loopable = true,
  1530. visible = el.tagName && win.getComputedStyle(el).display != 'none' && win.getComputedStyle(el).visibility != 'hidden';
  1531. while(loopable && visible) {
  1532. el = el.parentNode;
  1533.  
  1534. if(el && el.tagName && el.tagName!="BODY") {
  1535. visible = win.getComputedStyle(el).display != 'none' && win.getComputedStyle(el).visibility != 'hidden';
  1536. }else {
  1537. loopable = false;
  1538. }
  1539. }
  1540. return visible;
  1541. }
  1542.  
  1543. function getFormatJSON(obj){
  1544. if(!objIsArr(obj))return "";
  1545. let ret="[\n";
  1546. let len=obj.length,i=0,isLast;
  1547. obj.forEach(item=>{
  1548. ret+=" {\n";
  1549. let iLen=Object.keys(item).length,j=0;
  1550. for(let key in item){
  1551. isLast=(++j)==iLen;
  1552. let value=item[key];
  1553. if(objIsArr(value)){
  1554. let vstr="[",v=0,vIsLast=false;
  1555. value.forEach(vi=>{
  1556. vIsLast=(++v)==value.length;
  1557. vstr+="\""+vi.replace(/\\/g,"\\\\")+"\""+(vIsLast?"":",");
  1558. });
  1559. vstr+="]";
  1560. ret+=" \""+key+"\":"+vstr+""+(isLast?"":",")+"\n";
  1561. }else{
  1562. if(typeof value=="string"){
  1563. value=value.replace(/\\/g,"\\\\").replace(/"/g,"\\\"");
  1564. value="\""+value+"\"";
  1565. }
  1566. ret+=" \""+key+"\":"+value+""+(isLast?"":",")+"\n";
  1567. }
  1568. }
  1569. isLast=(++i)==len;
  1570. ret+=" }"+(isLast?"":",")+"\n";
  1571. });
  1572. ret+="]";
  1573. return ret;
  1574. }
  1575.  
  1576. function initRules(callback) {
  1577. /*0 wedata格式,1 pagetual格式*/
  1578. ruleUrls=[
  1579. {
  1580. id:0,
  1581. url:'https://raw.githubusercontent.com/hoothin/UserScripts/master/Pagetual/pagetualRules.json',
  1582. type:1
  1583. },
  1584. {
  1585. id:1,
  1586. url:'http://wedata.net/databases/AutoPagerize/items_all.json',
  1587. type:0,
  1588. }
  1589. ];var i=0,j=0;
  1590.  
  1591. ruleParser.initSavedRules(()=>{
  1592. storage.getItem("rulesData", data=>{
  1593. if(data){
  1594. rulesData=data;
  1595. if(data.urls)ruleUrls=ruleUrls.concat(data.urls);
  1596. if(data.sort){
  1597. let urls=[];
  1598. data.sort.forEach(id=>{
  1599. for(let s=0;s<ruleUrls.length;s++){
  1600. if(id==ruleUrls[s].id){
  1601. urls.push(ruleUrls[s]);
  1602. break;
  1603. }
  1604. }
  1605. });
  1606. ruleUrls=urls;
  1607. }
  1608. }
  1609. if(typeof(rulesData.opacity)=="undefined"){
  1610. rulesData.opacity=0.3;
  1611. }
  1612. if(typeof(rulesData.hideBar)=="undefined"){
  1613. rulesData.hideBar=true;
  1614. }
  1615. if(typeof(rulesData.dbClick2Stop)=="undefined"){
  1616. rulesData.dbClick2Stop=true;
  1617. }
  1618. if(typeof(rulesData.enableWhiteList)=="undefined"){
  1619. rulesData.enableWhiteList=false;
  1620. }
  1621. if(typeof(rulesData.enableHistory)=="undefined"){
  1622. rulesData.enableHistory=true;
  1623. }
  1624. if(typeof(rulesData.enableDebug)=="undefined"){
  1625. rulesData.enableDebug=true;
  1626. }
  1627. enableDebug=rulesData.enableDebug;
  1628. storage.getItem("forceState_"+location.host, v=>{
  1629. storage.getItem("ruleLastUpdate", date=>{
  1630. if(typeof(v)=="undefined"){
  1631. v=(rulesData.enableWhiteList?1:0);
  1632. }
  1633. forceState=v;
  1634. updateDate=date;
  1635. if(initConfig())return;
  1636. if(forceState==1)return;
  1637. let now=new Date().getTime();
  1638. if(!date || now-date>2*24*60*60*1000){
  1639. storage.setItem("ruleLastUpdate", now);
  1640. updateRules(()=>{
  1641. callback();
  1642. },(rule,err)=>{});
  1643. }else{
  1644. callback();
  1645. }
  1646. });
  1647. });
  1648. });
  1649. });
  1650. }
  1651.  
  1652. function requestDoc(url, callback){
  1653. _GM_xmlhttpRequest({
  1654. url: url,
  1655. method: 'GET',
  1656. overrideMimeType: 'text/html;charset='+document.charset,
  1657. headers: {
  1658. 'Referer': location.href
  1659. },
  1660. timeout: 5000,
  1661. onload: function(res) {
  1662. var doc=null;
  1663. try {
  1664. doc=document.implementation.createHTMLDocument('');
  1665. doc.documentElement.innerHTML=res.response;
  1666. }
  1667. catch (e) {
  1668. debug('parse error'+e.toString());
  1669. }
  1670. let pageElement=ruleParser.getPageElement(doc);
  1671. //只有1的話怕不是圖片哦
  1672. if(pageElement && (pageElement.length>1 || (pageElement.length==1 && pageElement[0].tagName!="IMG") )){
  1673. let result=ruleParser.insertPage(doc, pageElement, url, callback, false);
  1674. if(!result){
  1675. requestFromIframe(url, (doc, eles)=>{
  1676. loadPageOver();
  1677. if(eles){
  1678. ruleParser.insertPage(doc, eles, url, callback, true);
  1679. }
  1680. });
  1681. }
  1682. }else if(ruleParser.curSiteRule.singleUrl){
  1683. requestFromIframe(url, (doc, eles)=>{
  1684. loadPageOver();
  1685. if(eles){
  1686. ruleParser.insertPage(doc, eles, url, callback, true);
  1687. }
  1688. });
  1689. }else{
  1690. isPause=true;
  1691. callback(false);
  1692. }
  1693. },
  1694. onerror: function(e){
  1695. debug(e);
  1696. callback(false);
  1697. },
  1698. ontimeout: function(e){
  1699. debug(e);
  1700. callback(false);
  1701. }
  1702. });
  1703. }
  1704.  
  1705. var failFromIframe=0;
  1706. function requestFromIframe(url, callback){
  1707. let orgPage,curPage;
  1708. let iframe = document.createElement('iframe');
  1709. iframe.name = 'pagetual-iframe';
  1710. iframe.width = '100%';
  1711. iframe.height = '0';
  1712. iframe.frameBorder = '0';
  1713. if(ruleParser.curSiteRule.sandbox!=false){
  1714. iframe.sandbox="allow-same-origin allow-scripts allow-popups allow-forms";
  1715. }
  1716. iframe.style.cssText = 'margin:0!important;padding:0!important;visibility:hidden!important;';
  1717. iframe.addEventListener("load", e=>{
  1718. let waitTime=500,checkEval;
  1719. if(ruleParser.curSiteRule.wait){
  1720. if(isNaN(ruleParser.curSiteRule.wait)){
  1721. try{
  1722. checkEval=Function("doc",'"use strict";' + ruleParser.curSiteRule.wait);
  1723. }catch(e){
  1724. debug(e);
  1725. }
  1726. }else{
  1727. waitTime=ruleParser.curSiteRule.wait;
  1728. }
  1729. }
  1730. setTimeout(()=>{
  1731. let tryTimes=0;
  1732. function checkIframe(){
  1733. try{
  1734. let doc=iframe.contentDocument || iframe.contentWindow.document;
  1735. let eles=ruleParser.getPageElement(doc, iframe.contentWindow);
  1736. if(eles && eles.length>0 && (!checkEval || checkEval(doc))){
  1737. callback(doc, eles);
  1738. }else if(tryTimes++ < 10){
  1739. setTimeout(()=>{
  1740. checkIframe();
  1741. },waitTime);
  1742. return;
  1743. }else{
  1744. if(failFromIframe++ > 2){
  1745. failFromIframe=0;
  1746. debug("Stop as failFromIframe");
  1747. isPause=true;
  1748. callback(false, false);
  1749. }else{
  1750. callback(false, false);
  1751. }
  1752. }
  1753. }catch(e){
  1754. debug("Stop as cors");
  1755. //isPause=true;
  1756. ruleParser.curSiteRule.pageElement=allOfBody;
  1757. ruleParser.getInsert(true);
  1758. callback(false, false);
  1759. }
  1760. document.body.removeChild(iframe);
  1761. }
  1762. checkIframe();
  1763. },waitTime);
  1764. });
  1765. iframe.src=url;
  1766. document.body.appendChild(iframe);
  1767. }
  1768.  
  1769. function initPage(){
  1770. ruleParser.initPage(()=>{
  1771. if(ruleParser.nextLinkHref){
  1772. initView();
  1773. let isJs=/^(javascript|#)/.test(ruleParser.nextLinkHref.replace(location.href,""));
  1774. if(!isJs){
  1775. _GM_registerMenuCommand(i18n(forceState==2?"cancelForceIframe":"forceIframe"), ()=>{
  1776. storage.setItem("forceState_"+location.host, (forceState==2?"":2));
  1777. location.reload();
  1778. });
  1779. }
  1780. _GM_registerMenuCommand(i18n("loadNow"), ()=>{
  1781. let loadNum=window.prompt(i18n("loadConfirm"), "1");
  1782. if(loadNum==="" || loadNum===null)return;
  1783. autoLoadNum=Math.abs(parseInt(loadNum));
  1784. nextPage();
  1785. });
  1786. }
  1787. initListener();
  1788. nextPage();
  1789. });
  1790. }
  1791.  
  1792. function initView(){
  1793. _GM_addStyle(`
  1794. .pagetual_pageBar.stop {
  1795. -webkit-filter: invert(100%);
  1796. filter: invert(100%);
  1797. opacity: 1!important;
  1798. }
  1799. .pagetual_pageBar.hide {
  1800. display: none!important;
  1801. }
  1802. .pagetual_pageBar:hover {
  1803. opacity: 1!important;
  1804. }
  1805. .pagetual_pageBar span {
  1806. vertical-align: super;
  1807. }
  1808.  
  1809. .pagetual_pageBar span>svg:hover {
  1810. animation: touhouAni 1s infinite;
  1811. }
  1812. .pagetual_pageBar .pagetual_pageNum{
  1813. color: #55555f;
  1814. }
  1815. .pagetual_pageBar .pagetual_pageNum:hover{
  1816. color: #ff6464;
  1817. }
  1818.  
  1819. @keyframes touhouAni{
  1820. from {transform: rotate(0deg) scale3d(1.2, 1.2, 1.2);}
  1821. to {transform: rotate(360deg);}
  1822. }
  1823. @-webkit-keyframes touhouAni{
  1824. from {transform: rotate(0deg) scale3d(1.2, 1.2, 1.2);}
  1825. to {transform: rotate(360deg);}
  1826. }
  1827. `);
  1828. pageBarStyle=`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%);visibility: visible; position: initial; width: auto; height: 30px; float: none; clear: both; margin: 5px auto; text-align: center;`;
  1829. }
  1830. var loadingDiv=document.createElement("div");
  1831. loadingDiv.className="pagetual_loading";
  1832. 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;";
  1833. 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><svg width="120" height="30" viewBox="0 0 120 30" fill="#000000A0" style="display: block;position: initial;margin: auto;shape-rendering: auto;vertical-align: middle;visibility: visible;width: initial;height: initial;"><circle cx="15" cy="15" r="15"><animate attributeName="r" from="15" to="15" begin="0s" dur="0.8s" values="15;9;15" calcMode="linear" repeatCount="indefinite"></animate><animate attributeName="fill-opacity" from="1" to="1" begin="0s" dur="0.8s" values="1;.5;1" calcMode="linear" repeatCount="indefinite"></animate></circle><circle cx="60" cy="15" r="9" fill-opacity="0.3"><animate attributeName="r" from="9" to="9" begin="0s" dur="0.8s" values="9;15;9" calcMode="linear" repeatCount="indefinite"></animate><animate attributeName="fill-opacity" from="0.5" to="0.5" begin="0s" dur="0.8s" values=".5;1;.5" calcMode="linear" repeatCount="indefinite"></animate></circle><circle cx="105" cy="15" r="15"><animate attributeName="r" from="15" to="15" begin="0s" dur="0.8s" values="15;9;15" calcMode="linear" repeatCount="indefinite"></animate><animate attributeName="fill-opacity" from="1" to="1" begin="0s" dur="0.8s" values="1;.5;1" calcMode="linear" repeatCount="indefinite"></animate></circle></svg>`;
  1834.  
  1835. var upSvg=`<svg width="30" height="30" style="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>`;
  1836. var downSvg=`<svg width="30" height="30" style="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>`;
  1837. var pageBarStyle;
  1838. var initStyle=`display: initial;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: 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;`;
  1839. 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);`;
  1840.  
  1841. var isPause=false,isLoading=false,curPage=1,forceState=0,bottomGap=1000,autoLoadNum=-1;
  1842.  
  1843. function changeStop(stop, hide){
  1844. isPause=stop;
  1845. [].forEach.call(document.querySelectorAll(".pagetual_pageBar"), bar=>{
  1846. if(isPause){
  1847. bar.classList.add("stop");
  1848. if(hide)bar.classList.add("hide");
  1849. }else{
  1850. bar.classList.remove("stop");
  1851. if(hide)bar.classList.remove("hide");
  1852. }
  1853. });
  1854. }
  1855.  
  1856. function isInViewPort(element) {
  1857. if(!element.parentNode)return false;
  1858. if(_unsafeWindow.getComputedStyle(element).display=="none")return false;
  1859. const viewWidth = window.innerWidth || document.documentElement.clientWidth;
  1860. const viewHeight = window.innerHeight || document.documentElement.clientHeight;
  1861. const {
  1862. top,
  1863. right,
  1864. bottom,
  1865. left,
  1866. } = element.getBoundingClientRect();
  1867.  
  1868. return (
  1869. top >= 0 &&
  1870. left >= 0 &&
  1871. right <= viewWidth &&
  1872. bottom <= viewHeight
  1873. );
  1874. }
  1875.  
  1876. var urlChanged=false;
  1877. var _wr = function(type) {
  1878. var orig = history[type];
  1879. return function() {
  1880. var rv = orig.apply(this, arguments);
  1881. var e = new Event(type);
  1882. e.arguments = arguments;
  1883. window.dispatchEvent(e);
  1884. return rv;
  1885. };
  1886. };
  1887. history.pushState = _wr('pushState');
  1888. window.addEventListener('pushState', function(e) {
  1889. urlChanged=true;
  1890. isPause=true;
  1891. setTimeout(()=>{
  1892. if(location.href==configPage){
  1893. location.reload();
  1894. }
  1895. },1);
  1896. });
  1897.  
  1898. function initListener(){
  1899. let loadmoreBtn,loading=true;
  1900. setTimeout(()=>{
  1901. loadmoreBtn=getLoadMore(document);
  1902. if(loadmoreBtn && isVisible(loadmoreBtn, _unsafeWindow)){
  1903. loading=false;
  1904. }
  1905. },500);
  1906. let checkScrollReach=()=>{
  1907. let scrolly=window.scrollY;
  1908. let windowHeight=window.innerHeight || document.documentElement.clientHeight;
  1909. let scrollH=Math.max(document.documentElement.scrollHeight, document.body.scrollHeight);
  1910. if(scrollH-scrolly-windowHeight<bottomGap){
  1911. nextPage();
  1912. }
  1913. };
  1914. document.addEventListener('scroll', e=>{
  1915. if(urlChanged){
  1916. ruleParser.initPage(()=>{
  1917. if(ruleParser.nextLinkHref)initView();
  1918. });
  1919. urlChanged=false;
  1920. isPause=false;
  1921. }
  1922. if(isPause)return;
  1923. if(!loading){
  1924. loading=true;
  1925. setTimeout(()=>{loading=false},200);
  1926. if(!loadmoreBtn || !loadmoreBtn.parentNode){
  1927. loadmoreBtn=getLoadMore(document);
  1928. }
  1929. if(loadmoreBtn){
  1930. if(isInViewPort(loadmoreBtn)){
  1931. emuClick(loadmoreBtn);
  1932. }
  1933. }
  1934. }
  1935. setTimeout(()=>{
  1936. if(!isLoading){
  1937. checkScrollReach();
  1938. }
  1939. },100);
  1940. }, true);
  1941. document.addEventListener('dblclick', e=>{
  1942. if(rulesData.dbClick2Stop){
  1943. setTimeout(()=>{
  1944. changeStop(!isPause, rulesData.hideBar);
  1945. if(!isPause){
  1946. checkScrollReach();
  1947. }
  1948. },200);
  1949. }
  1950. });
  1951. }
  1952.  
  1953. function getLoadMore(doc){
  1954. if(ruleParser.curSiteRule.loadMore==="")return null;
  1955. let btnSel=ruleParser.curSiteRule.loadMore||".LoadMore,.load-more";
  1956. let loadmoreBtn=doc.querySelector(btnSel);
  1957. if(!loadmoreBtn){
  1958. let buttons=doc.querySelectorAll("input,button,a,div[onclick]"),loadmoreReg=/^\s*(加载更多|加載更多|load\s*more|もっと読み込む)\s*$/i;
  1959. for(let i=0;i<buttons.length;i++){
  1960. let button=buttons[i];
  1961. if(button && loadmoreReg.test(button.innerText)){
  1962. loadmoreBtn=button;
  1963. break;
  1964. }
  1965. }
  1966. }
  1967. return loadmoreBtn;
  1968. }
  1969.  
  1970. var hasPageNum=true;
  1971. function createPageBar(url){
  1972. let insert=ruleParser.getInsert();
  1973. if(!insert || !insert.parentNode)return;
  1974. curPage++;
  1975. if(rulesData.opacity==0)return;
  1976. let example=ruleParser.curSiteRule.insertPos==2?insert.children[0]:(insert.previousElementSibling||insert);
  1977. let inTable=example.parentNode.tagName=="TABLE" ||
  1978. example.tagName=="TR" ||
  1979. example.tagName=="TBODY" ||
  1980. (example.previousElementSibling && example.previousElementSibling.tagName=="TR") ||
  1981. (example.previousElementSibling && example.previousElementSibling.tagName=="TBODY");
  1982. let inLi=example.tagName=="LI" || (example.previousElementSibling && example.previousElementSibling.tagName=="LI");
  1983. let pageBar=document.createElement(inTable?"tr":(inLi?"li":"div"));
  1984. let upSpan=document.createElement("span");
  1985. let downSpan=document.createElement("span");
  1986. let pageText=document.createElement("a");
  1987. let pageNum;
  1988. pageBar.className="pagetual_pageBar";
  1989. pageBar.id="pagetual_pageBar";
  1990. if(isPause){
  1991. pageBar.classList.add("stop");
  1992. }
  1993. pageBar.style.cssText=pageBarStyle;
  1994. pageBar.title=i18n(isPause?"enable":"disable");
  1995. upSpan.innerHTML=upSvg;
  1996. upSpan.title=i18n("toTop");
  1997. downSpan.innerHTML=downSvg;
  1998. downSpan.title=i18n("toBottom");
  1999. upSpan.style.cssText=initStyle;
  2000. downSpan.style.cssText=initStyle;
  2001. pageText.href=url;
  2002. pageText.style.cssText=pageTextStyle;
  2003. pageText.title=i18n("current");
  2004. pageBar.appendChild(upSpan);
  2005. pageBar.appendChild(pageText);
  2006. if(ruleParser.curSiteRule.pageNum || (hasPageNum && /[&\/\?](p=|page[=\/])\d+/.test(url))){
  2007. pageText.innerHTML="Page ";
  2008. pageNum=document.createElement("span");
  2009. pageNum.innerText=curPage;
  2010. pageNum.className="pagetual_pageNum";
  2011. pageNum.title=i18n("inputPageNum");
  2012. pageNum.style.cssText=pageTextStyle;
  2013. pageNum.style.cursor="pointer";
  2014. pageNum.style.color="";
  2015. pageNum.addEventListener("click", e=>{
  2016. let pageInput=prompt(i18n("inputPageNum"));
  2017. if(pageInput){
  2018. let pageLink=ruleParser.getLinkByPage(url, pageInput);
  2019. if(pageLink){
  2020. _GM_openInTab(pageLink,{active:true});
  2021. }
  2022. }
  2023. e.preventDefault();
  2024. e.stopPropagation();
  2025. });
  2026. pageBar.appendChild(pageNum);
  2027. }else{
  2028. pageText.innerHTML="Page "+curPage;
  2029. hasPageNum=false;
  2030. }
  2031. pageBar.appendChild(downSpan);
  2032. let parentStyle=_unsafeWindow.getComputedStyle(example.parentNode);
  2033. pageBar.style.width=parentStyle.width;
  2034. if(parentStyle.display=="grid" || parentStyle.display=="inline-grid"){
  2035. pageBar.style.gridColumnStart=1;
  2036. pageBar.style.gridColumnEnd=1+parseInt(example.parentNode.offsetWidth/example.offsetWidth);
  2037. }
  2038. if(inTable){
  2039. example=(example.tagName=="TR" || example.tagName=="TBODY")?example:example.previousElementSibling;
  2040. if(example.previousElementSibling)example=example.previousElementSibling;
  2041. let tdNum=0;
  2042. [].forEach.call(example.querySelectorAll("td,th"), td=>{
  2043. tdNum+=td.colSpan||1;
  2044. });
  2045. pageBar.style.display="table-row";
  2046. pageBar.style.backgroundColor="unset";
  2047. let td=document.createElement("td");
  2048. td.style.backgroundColor="rgb(240 240 240 / 80%)";
  2049. td.style.borderRadius="20px";
  2050. td.colSpan=tdNum||1;
  2051. td.style.padding="0 0";
  2052. td.style.textAlign="center";
  2053. td.appendChild(upSpan);
  2054. td.appendChild(pageText);
  2055. if(pageNum)td.appendChild(pageNum);
  2056. td.appendChild(downSpan);
  2057. pageBar.appendChild(td);
  2058. }else if(inLi){
  2059. example=example.tagName=="LI"?example:example.previousElementSibling;
  2060. pageBar.style.display="table-row";
  2061. pageBar.style.backgroundColor="unset";
  2062. let td=document.createElement("td");
  2063. td.style.backgroundColor="rgb(240 240 240 / 80%)";
  2064. td.style.borderRadius="20px";
  2065. td.colSpan=example.children.length;
  2066. td.style.padding="0 0";
  2067. td.style.textAlign="center";
  2068. td.style.minWidth="150px";
  2069. td.appendChild(upSpan);
  2070. td.appendChild(pageText);
  2071. td.style.width=pageBar.style.width;
  2072. if(pageNum)td.appendChild(pageNum);
  2073. td.appendChild(downSpan);
  2074. pageBar.appendChild(td);
  2075. }
  2076.  
  2077. upSpan.addEventListener("click", e=>{
  2078. document.body.scrollTop=0;
  2079. document.documentElement.scrollTop=0;
  2080. e.preventDefault();
  2081. e.stopPropagation();
  2082. });
  2083. downSpan.addEventListener("click", e=>{
  2084. changeStop(true);
  2085. pageBar.title=i18n(isPause?"enable":"disable");
  2086. document.body.scrollTop=9999999;
  2087. document.documentElement.scrollTop=9999999;
  2088. e.preventDefault();
  2089. e.stopPropagation();
  2090. });
  2091. pageBar.addEventListener("click", e=>{
  2092. changeStop(!isPause);
  2093. pageBar.title=i18n(isPause?"enable":"disable");
  2094. });
  2095. pageText.addEventListener("click", e=>{
  2096. e.stopPropagation();
  2097. });
  2098. if(ruleParser.curSiteRule.insertPos==2){
  2099. insert.appendChild(pageBar);
  2100. }else{
  2101. insert.parentNode.insertBefore(pageBar, insert);
  2102. }
  2103. if(ruleParser.curSiteRule.pageBar){
  2104. try{
  2105. Function("pageBar",'"use strict";' + ruleParser.curSiteRule.pageBar)(pageBar);
  2106. }catch(e){
  2107. debug(e);
  2108. }
  2109. }
  2110.  
  2111. let scrollH=Math.max(document.documentElement.scrollHeight, document.body.scrollHeight);
  2112. let posEle=pageBar.nextElementSibling||pageBar;
  2113. while(posEle && !posEle.offsetParent){
  2114. posEle=posEle.previousElementSibling||posEle.parentNode;
  2115. }
  2116. if(posEle){
  2117. let actualTop = posEle.offsetTop;
  2118. let current = posEle.parentNode.offsetParent;
  2119. while (current !== null){
  2120. actualTop += current.offsetTop;
  2121. current = current.offsetParent;
  2122. }
  2123. bottomGap=scrollH-actualTop+(window.innerHeight||document.documentElement.clientHeight)*(ruleParser.curSiteRule.rate||1);
  2124. }else{
  2125. bottomGap=1000;
  2126. }
  2127. return pageBar;
  2128. }
  2129.  
  2130. function emuClick(btn){
  2131. if(!PointerEvent)return btn.click();
  2132. let eventParam={
  2133. isTrusted: true,
  2134. altKey: false,
  2135. azimuthAngle: 0,
  2136. bubbles: true,
  2137. button: 0,
  2138. buttons: 0,
  2139. clientX: 1,
  2140. clientY: 1,
  2141. cancelBubble: false,
  2142. cancelable: true,
  2143. composed: true,
  2144. ctrlKey: false,
  2145. defaultPrevented: false,
  2146. detail: 1,
  2147. eventPhase: 2,
  2148. fromElement: null,
  2149. height: 1,
  2150. isPrimary: false,
  2151. metaKey: false,
  2152. pointerId: 1,
  2153. pointerType: "mouse",
  2154. pressure: 0,
  2155. relatedTarget: null,
  2156. returnValue: true,
  2157. shiftKey: false,
  2158. toElement: null,
  2159. twist: 0,
  2160. type: "click",
  2161. which: 1
  2162. };
  2163. var mouseclick = new PointerEvent("click",eventParam);
  2164. btn.dispatchEvent(mouseclick);
  2165. }
  2166.  
  2167. var emuIframe;
  2168. function emuPage(callback){
  2169. let orgPage,curPage,iframeDoc,times=0,loadmoreBtn,loadmoreEnd=false,waitTimes=10;
  2170. function checkPage(){
  2171. if(isPause)return;
  2172. try{
  2173. iframeDoc=emuIframe.contentDocument || emuIframe.contentWindow.document;
  2174. }catch(e){
  2175. debug("Stop as cors");
  2176. isPause=true;
  2177. callback(false, false);
  2178. return;
  2179. }
  2180.  
  2181. let nextLink=ruleParser.getNextLink(iframeDoc);
  2182. let waitTime=500,checkEval;
  2183. if(ruleParser.curSiteRule.wait){
  2184. if(isNaN(ruleParser.curSiteRule.wait)){
  2185. try{
  2186. checkEval=Function("doc",'"use strict";' + ruleParser.curSiteRule.wait);
  2187. }catch(e){
  2188. debug(e);
  2189. }
  2190. }else{
  2191. waitTime=ruleParser.curSiteRule.wait;
  2192. }
  2193. }
  2194.  
  2195. if(!orgPage){
  2196. if(!loadmoreEnd){
  2197. loadmoreBtn=getLoadMore(iframeDoc);
  2198. if(loadmoreBtn && isVisible(loadmoreBtn, iframeDoc.defaultView)){
  2199. emuClick(loadmoreBtn);
  2200. let intv=setInterval(()=>{
  2201. loadmoreBtn=getLoadMore(iframeDoc);
  2202. if(!loadmoreBtn || !loadmoreBtn.parentNode || !isVisible(loadmoreBtn, iframeDoc.defaultView)){
  2203. clearInterval(intv);
  2204. loadmoreEnd=true;
  2205. setTimeout(()=>{
  2206. checkPage();
  2207. },500);
  2208. }else{
  2209. emuClick(loadmoreBtn);
  2210. }
  2211. },200);
  2212. return;
  2213. }else{
  2214. loadmoreEnd=true;
  2215. }
  2216. }
  2217. let pageEle=ruleParser.getPageElement(iframeDoc, iframeDoc.defaultView, true);
  2218. if(!nextLink || !pageEle || (checkEval && !checkEval(iframeDoc))){
  2219. if(ruleParser.curSiteRule.wait && waitTimes-->0){
  2220. setTimeout(()=>{
  2221. checkPage();
  2222. },waitTime);
  2223. return;
  2224. }
  2225. }
  2226. orgPage=pageEle;
  2227. if(!orgPage || orgPage.length==0){
  2228. debug("Stop as no page when emu");
  2229. isPause=true;
  2230. callback(false, false);
  2231. return;
  2232. }
  2233. if(orgPage && orgPage[0].tagName=="UL")orgPage=orgPage[0].children;
  2234. if(orgPage && nextLink){
  2235. orgPage=orgPage[parseInt(orgPage.length/2)];
  2236. if(!isVisible(nextLink, iframeDoc.defaultView)){
  2237. debug("Stop as next hide when emu");
  2238. isPause=true;
  2239. callback(false, false);
  2240. }else{
  2241. emuClick(nextLink);
  2242. setTimeout(()=>{
  2243. checkPage();
  2244. },500);
  2245. }
  2246. }else{
  2247. debug("Stop as no next when emu");
  2248. isPause=true;
  2249. callback(false, false);
  2250. }
  2251. return;
  2252. }
  2253. if(times++ > 20){
  2254. //emuClick(nextLink);
  2255. debug("Stop as timeout when emu");
  2256. isPause=true;
  2257. callback(false, false);
  2258. return;
  2259. }
  2260. let eles=ruleParser.getPageElement(iframeDoc, iframeDoc.defaultView, true),checkItem=eles;
  2261. if(eles && eles.length>0 && eles[0].tagName=="UL")checkItem=eles[0].children;
  2262. if(!eles || eles.length==0 || orgPage == checkItem[parseInt(checkItem.length/2)] || (checkEval && !checkEval(iframeDoc))){
  2263. setTimeout(()=>{
  2264. checkPage();
  2265. },waitTime);
  2266. }else{
  2267. callback(iframeDoc, eles);
  2268. }
  2269. }
  2270. if(!emuIframe){
  2271. emuIframe = document.createElement('iframe');
  2272. emuIframe.name = 'pagetual-iframe';
  2273. if(ruleParser.curSiteRule.sandbox!=false){
  2274. emuIframe.sandbox="allow-same-origin allow-scripts allow-popups allow-forms";
  2275. }
  2276. emuIframe.width = '100%';
  2277. emuIframe.height = '0';
  2278. emuIframe.frameBorder = '0';
  2279. emuIframe.style.cssText = 'margin:0!important;padding:0!important;visibility:hidden!important;';
  2280. emuIframe.addEventListener("load", e=>{
  2281. setTimeout(()=>{
  2282. try{
  2283. iframeDoc=emuIframe.contentDocument || emuIframe.contentWindow.document;
  2284. }catch(e){
  2285. debug("Stop as cors");
  2286. isPause=true;
  2287. callback(false, false);
  2288. return;
  2289. }
  2290. let code=ruleParser.curSiteRule.init;
  2291. if(code){
  2292. try{
  2293. Function('doc','"use strict";' + code)(iframeDoc);
  2294. }catch(e){
  2295. debug(e);
  2296. }
  2297. }
  2298. checkPage();
  2299. },500);
  2300. });
  2301. emuIframe.src=location.href;
  2302. document.body.appendChild(emuIframe);
  2303. }else{
  2304. checkPage();
  2305. }
  2306. }
  2307.  
  2308. function forceIframe(url, callback){
  2309. let curIframe = document.createElement('iframe'),iframeDoc;
  2310. curIframe.name = 'pagetual-iframe';
  2311. curIframe.sandbox="allow-same-origin allow-scripts allow-popups allow-forms";
  2312. curIframe.frameBorder = '0';
  2313. curIframe.scrolling="no";
  2314. 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;';
  2315. curIframe.addEventListener("load", e=>{
  2316. try{
  2317. iframeDoc=curIframe.contentDocument || curIframe.contentWindow.document;
  2318. }catch(e){
  2319. debug("Stop as cors");
  2320. isPause=true;
  2321. callback(false, false);
  2322. return;
  2323. }
  2324. ruleParser.insertPage(iframeDoc, [], url, null, true);
  2325. callback(curIframe, true);
  2326. curIframe.style.height=iframeDoc.body.scrollHeight+"px";
  2327. curIframe.style.width=iframeDoc.body.scrollWidth+"px";
  2328. });
  2329. let inAction=false;
  2330. let forceRefresh=e=>{
  2331. if(inAction || !iframeDoc)return;
  2332. inAction=true;
  2333. setTimeout(()=>{
  2334. inAction=false;
  2335. curIframe.style.height=iframeDoc.body.scrollHeight+"px";
  2336. curIframe.style.width=iframeDoc.body.scrollWidth+"px";
  2337. if(!ruleParser.nextLinkHref){
  2338. ruleParser.getNextLink(iframeDoc);
  2339. if(ruleParser.nextLinkHref){
  2340. document.removeEventListener("scroll", forceRefresh);
  2341. }
  2342. }else{
  2343. document.removeEventListener("scroll", forceRefresh);
  2344. }
  2345. },500);
  2346. curIframe.style.height=iframeDoc.body.scrollHeight+"px";
  2347. curIframe.style.width=iframeDoc.body.scrollWidth+"px";
  2348. };
  2349. document.addEventListener("scroll", forceRefresh);
  2350. curIframe.src=url;
  2351. let insert=ruleParser.getInsert();
  2352. document.body.appendChild(curIframe);
  2353. return curIframe;
  2354. }
  2355.  
  2356. function loadPageOver(){
  2357. isLoading=false;
  2358. if(loadingDiv.parentNode){
  2359. loadingDiv.parentNode.removeChild(loadingDiv);
  2360. }
  2361. setTimeout(()=>{
  2362. let scrollH=Math.max(document.documentElement.scrollHeight, document.body.scrollHeight);
  2363. if(scrollH < (window.innerHeight || document.documentElement.clientHeight)){
  2364. nextPage();
  2365. }
  2366. },1);
  2367. }
  2368.  
  2369. function nextPage(){
  2370. if(isPause || isLoading)return;
  2371. let nextLink=ruleParser.nextLinkHref;
  2372. if(!nextLink)return;
  2373. let insert=ruleParser.getInsert();
  2374. if(insert){
  2375. let isJs=/^(javascript|#)/.test(nextLink.replace(location.href,""));
  2376. if(location.protocol=="https:" && /^http:/.test(nextLink)){
  2377. nextLink=nextLink.replace(/^http/,"https");
  2378. }
  2379. isLoading=true;
  2380. document.body.appendChild(loadingDiv);
  2381. let sleep=ruleParser.curSiteRule.sleep||0;
  2382. setTimeout(()=>{
  2383. if(ruleParser.curSiteRule.pageElementByJs){
  2384. var over=ele=>{
  2385. loadPageOver();
  2386. if(ele){
  2387. createPageBar(nextLink);
  2388. ruleParser.insertPage(null, ele, nextLink, null, true);
  2389. if(autoLoadNum>=0){
  2390. if(autoLoadNum!=0 && --autoLoadNum==0){
  2391. autoLoadNum=-1;
  2392. }else{
  2393. nextPage();
  2394. }
  2395. }
  2396. }else{
  2397. debug("Stop as no page when get by js");
  2398. isPause=true;
  2399. }
  2400. };
  2401. try{
  2402. Function("over",'"use strict";' + ruleParser.curSiteRule.pageElementByJs)(over);
  2403. }catch(e){
  2404. debug(e);
  2405. }
  2406. }else if(ruleParser.curSiteRule.action==1 && !isJs){
  2407. requestFromIframe(nextLink, (doc, eles)=>{
  2408. loadPageOver();
  2409. if(eles){
  2410. createPageBar(nextLink);
  2411. ruleParser.insertPage(doc, eles, nextLink, null, true);
  2412. if(autoLoadNum>=0){
  2413. if(autoLoadNum!=0 && --autoLoadNum==0){
  2414. autoLoadNum=-1;
  2415. }else{
  2416. nextPage();
  2417. }
  2418. }
  2419. }
  2420. });
  2421. }else if((forceState==2||ruleParser.curSiteRule.action==2) && !isJs){
  2422. forceIframe(nextLink, (iframe, eles)=>{
  2423. loadPageOver();
  2424. let pageBar=createPageBar(nextLink);
  2425. iframe.parentNode.insertBefore(pageBar, iframe);
  2426. if(autoLoadNum>=0){
  2427. if(autoLoadNum!=0 && --autoLoadNum==0){
  2428. autoLoadNum=-1;
  2429. }else{
  2430. nextPage();
  2431. }
  2432. }
  2433. });
  2434. }else{
  2435. if(!isJs){
  2436. requestDoc(nextLink, (eles)=>{
  2437. loadPageOver();
  2438. if(eles){
  2439. createPageBar(nextLink);
  2440. if(autoLoadNum>=0){
  2441. if(autoLoadNum!=0 && --autoLoadNum==0){
  2442. autoLoadNum=-1;
  2443. }else{
  2444. nextPage();
  2445. }
  2446. }
  2447. }
  2448. });
  2449. }else{
  2450. emuPage((doc, eles)=>{
  2451. loadPageOver();
  2452. if(eles){
  2453. createPageBar(nextLink);
  2454. ruleParser.insertPage(doc, eles, "", null, true);
  2455. if(autoLoadNum>=0){
  2456. if(autoLoadNum!=0 && --autoLoadNum==0){
  2457. autoLoadNum=-1;
  2458. }else{
  2459. nextPage();
  2460. }
  2461. }
  2462. }
  2463. });
  2464. }
  2465. }
  2466. },sleep);
  2467. }
  2468. }
  2469.  
  2470. function init(){
  2471. initRules(()=>{
  2472. initPage();
  2473. });
  2474. }
  2475. setTimeout(()=>{
  2476. init();
  2477. },300);
  2478. })();

QingJ © 2025

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