东方永页机

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

当前为 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.2
  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.href || /^javascript:/.test(aTag.href)){
  855. if(!nextJs1)nextJs1=aTag;
  856. }else{
  857. next1=aTag;
  858. }
  859. }
  860. }
  861. if(!next2){
  862. if(/^\s*[下后後][一1]?[章话話]/i.test(aTag.innerText)){
  863. if(!aTag.href || /^javascript:/.test(aTag.href)){
  864. if(!nextJs2)nextJs2=aTag;
  865. }else{
  866. next2=aTag;
  867. }
  868. }
  869. }
  870. if(!next3){
  871. if(aTag.innerText=="&gt;" || aTag.innerText=="▶" || aTag.innerText==">" || aTag.innerText=="›" || /nextpage/i.test(aTag.className)){
  872. if(!aTag.href || /^javascript:/.test(aTag.href)){
  873. if(!nextJs3)nextJs3=aTag;
  874. }else{
  875. next3=aTag;
  876. }
  877. }
  878. }
  879. if(!aTag.href || /^javascript:/.test(aTag.href))continue;
  880. if(!next4){
  881. if(aTag.href.replace("?&","?").replace("#!","").replace("index.php?","?").replace(preStr,"").replace(afterStr,"")==parseInt(pageNum)+1){
  882. next4=aTag;
  883. }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,""))){
  884. let curHref=aTag.getAttribute("href");
  885. let pageOne=curHref.replace(/\/2(\/|\?|&|$)/,"/1$1");
  886. if(pageOne==curHref)pageOne=null;
  887. else pageOne=curPage.querySelector(`a[href='${pageOne}']`);
  888. if(!pageOne)next4=aTag;
  889. }
  890. }
  891. }
  892. next=next1||next3||next4||next2||nextJs1||nextJs3||nextJs2;
  893. }
  894. if(!next)next=jsNext;
  895. if(next && next.classList.contains("results-more"))next=null;
  896. return {next:next,canSave:canSave};
  897. }
  898.  
  899. canonicalUri(src, base_path) {
  900. if(src.charAt(0)=="#")return location.href+src;
  901. var root_page = /^[^?#]*\//.exec(location.href)[0],
  902. root_domain = /^\w+\:\/\/\/?[^\/]+/.exec(root_page)[0],
  903. absolute_regex = /^\w+\:\/\//;
  904. src=src.replace(/\.\//,"");
  905. if (/^\/\/\/?/.test(src)){
  906. src = location.protocol + src;
  907. }
  908. else if (!absolute_regex.test(src) && src.charAt(0) != "/"){
  909. src = (base_path || "") + src;
  910. }
  911. return (absolute_regex.test(src) ? src : ((src.charAt(0) == "/" ? root_domain : root_page) + src));
  912. }
  913.  
  914. getLinkByPage(url, pageNum) {
  915. if(!url)return;
  916. if(this.curSiteRule.pageNum){
  917. let result=this.curSiteRule.pageNum;
  918. let strMatch=result.match(/\{.*?}/);
  919. if(!strMatch)return null;
  920. let urlReg=new RegExp("("+result.replace(strMatch[0], ")\\d+(")+")");
  921. let code=strMatch[0].replace(/^{/,"").replace(/}$/,"").replace(/\$p/g,pageNum);
  922. if(code==pageNum){
  923. result=url.replace(urlReg,"$1"+code+"$2");
  924. }else{
  925. try{
  926. code=Function('"use strict";return ' + code)();
  927. result=url.replace(urlReg,"$1"+code+"$2");
  928. }catch(e){
  929. debug(e);
  930. }
  931. }
  932. return result==url?url.replace(/([&\/\?](p=|page[=\/]))\d+/i, "$1"+pageNum):result;
  933. }else{
  934. return url.replace(/([&\/\?](p=|page[=\/]))\d+/i, "$1"+pageNum);
  935. }
  936. }
  937.  
  938. getNextLink(doc) {
  939. let nextLink=null,page;
  940. if(this.curSiteRule.pageElementByJs){
  941. this.nextLinkHref="#";
  942. return true;
  943. }else if(this.curSiteRule.nextLinkByJs){
  944. try{
  945. let targetUrl=Function("doc",'"use strict";' + this.curSiteRule.nextLinkByJs)(doc);
  946. if(targetUrl)nextLink={href:targetUrl};
  947. }catch(e){
  948. debug(e);
  949. }
  950. }else if(this.curSiteRule.nextLinkByUrl){
  951. let targetUrl=this.curUrl.replace(new RegExp(this.curSiteRule.nextLinkByUrl[0]), this.curSiteRule.nextLinkByUrl[1]);
  952. if(targetUrl != this.curUrl){
  953. let reps=targetUrl.match(/{.*?}/g);
  954. if(reps){
  955. reps.forEach(rep=>{
  956. let code=rep.replace("{","").replace("}","");
  957. let result=code.match(/^(\d+)\+1$/);
  958. if(result){
  959. result=parseInt(result[1])+1;
  960. }else{
  961. try{
  962. result=Function('"use strict";return ' + code)();
  963. }catch(e){
  964. debug(e);
  965. }
  966. }
  967. targetUrl=targetUrl.replace(rep, result);
  968. });
  969. }
  970. }
  971. nextLink={href:targetUrl};
  972. }else if(this.curSiteRule.nextLink){
  973. if(this.curSiteRule.nextLink!="0"){
  974. nextLink=this.curSiteRule.type==0?getElementByXpath(this.curSiteRule.nextLink,doc,doc):doc.querySelector(this.curSiteRule.nextLink);
  975. }
  976. }else{
  977. page=this.getPage(doc);
  978. nextLink=page.next;
  979. if(nextLink){
  980. if(nextLink.tagName=="INPUT" && nextLink.parentNode.tagName=="FORM"){
  981. let params=[];
  982. let form=nextLink.parentNode;
  983. [].forEach.call(form.querySelectorAll("input"), input=>{
  984. params.push(input.name+'='+input.value);
  985. });
  986. nextLink.href=form.action+'?'+params.join('&');
  987. }
  988. if(nextLink.classList.contains("noClick")){
  989. this.nextLinkHref=false;
  990. return null;
  991. }else if(doc==document){
  992. if((!nextLink.href || /^javascript:/.test(nextLink.href)) && !isVisible(nextLink, _unsafeWindow)){
  993. this.nextLinkHref=false;
  994. return null;
  995. }else{
  996. let nextLinkCs=_unsafeWindow.getComputedStyle(nextLink);
  997. if(nextLinkCs.cursor=="not-allowed"){
  998. this.nextLinkHref=false;
  999. return null;
  1000. }
  1001. }
  1002. }
  1003. }
  1004. }
  1005. if(nextLink){
  1006. if(nextLink.href && nextLink.href==this.curUrl){
  1007. nextLink=null;
  1008. }else if(/^javascript:/.test(nextLink.href) && (this.curSiteRule.action==0 || this.curSiteRule.action==1)){
  1009. nextLink=null;
  1010. }
  1011. /*if(!this.curSiteRule.nextLink && page && page.canSave){
  1012. this.curSiteRule.nextLink=this.geneSelector(nextLink);
  1013. this.curSiteRule.type=1;
  1014. this.saveCurSiteRule();
  1015. }*/
  1016. }
  1017. if(nextLink){
  1018. this.nextLinkHref=(nextLink.href && !/^javascript:/.test(nextLink.href))?this.canonicalUri(nextLink.href):"#";
  1019. debug(nextLink);
  1020. }else{
  1021. this.nextLinkHref=false;
  1022. }
  1023. return nextLink;
  1024. }
  1025.  
  1026. getInsert(refresh) {
  1027. if(refresh){
  1028. this.insert=null;
  1029. }
  1030. if(this.insert && !refresh){
  1031. let parent=this.insert;
  1032. while(parent && parent.nodeName!="BODY"){
  1033. parent=parent.parentNode;
  1034. }
  1035. if(parent && parent.nodeName=="BODY"){
  1036. return this.insert;
  1037. }
  1038. }
  1039. if(this.curSiteRule.insert){
  1040. this.insert=this.curSiteRule.type==0?getElementByXpath(this.curSiteRule.insert,document):document.querySelector(this.curSiteRule.insert);
  1041. }else{
  1042. let pageElement=this.getPageElement(document, _unsafeWindow);
  1043. if(pageElement && pageElement.length>0){
  1044. var pELast = pageElement[pageElement.length - 1];
  1045. this.insert = pELast.nextSibling ? pELast.nextSibling : pELast.parentNode.appendChild(document.createTextNode(' '));
  1046. }
  1047. }
  1048. return this.insert;
  1049. }
  1050.  
  1051. pageInit(doc,eles){
  1052. let code=this.curSiteRule.pageInit;
  1053. if(code){
  1054. try{
  1055. Function("doc","eles",'"use strict";' + code)(doc,eles);
  1056. }catch(e){
  1057. debug(e);
  1058. }
  1059. }
  1060. }
  1061.  
  1062. pageAction(doc,eles){
  1063. let code=this.curSiteRule.pageAction;
  1064. if(code){
  1065. try{
  1066. Function("doc","eles",'"use strict";' + code)(doc,eles);
  1067. }catch(e){
  1068. debug(e);
  1069. }
  1070. }
  1071. let setLazyImg=img=>{
  1072. let realSrc;
  1073. if(img.getAttribute("_src") && !img.src){
  1074. realSrc=img.getAttribute("_src");
  1075. }else if(img.dataset && img.dataset.original){
  1076. realSrc=img.dataset.original;
  1077. }else if(img.dataset && img.dataset.src){
  1078. realSrc=img.dataset.src;
  1079. }else if(img._lazyrias && img._lazyrias.srcset){
  1080. realSrc=img._lazyrias.srcset[img._lazyrias.srcset.length-1];
  1081. }else if(img.dataset && img.dataset.origFile){
  1082. realSrc=img.dataset.origFile;
  1083. }else if(img.srcset){
  1084. var srcs=img.srcset.split(","),largeSize=0;
  1085. srcs.forEach(srci=>{
  1086. let srcInfo=srci.trim().split(" "),curSize=parseInt(srcInfo[1]);
  1087. if(srcInfo[1] && curSize>largeSize){
  1088. largeSize=curSize;
  1089. realSrc=srcInfo[0];
  1090. }
  1091. });
  1092. }
  1093. if(realSrc){
  1094. img.src=realSrc;
  1095. img.style.display="block";
  1096. }
  1097. };
  1098. [].forEach.call(eles, ele=>{
  1099. if(ele.tagName=="IMG"){
  1100. setLazyImg(ele);
  1101. }else{
  1102. [].forEach.call(ele.querySelectorAll("img"), img=>{
  1103. setLazyImg(img);
  1104. });
  1105. }
  1106. if(ele.tagName=="A" && ele.classList.contains("lazyload")){
  1107. if(ele.dataset.original){
  1108. ele.style.backgroundImage='url("'+ele.dataset.original+'")';
  1109. }
  1110. }else{
  1111. [].forEach.call(ele.querySelectorAll("a.lazyload"), a=>{
  1112. if(a.dataset.original){
  1113. a.style.backgroundImage='url("'+a.dataset.original+'")';
  1114. }
  1115. });
  1116. }
  1117. });
  1118. let lazyImgSrc=this.curSiteRule.lazyImgSrc;
  1119. if(lazyImgSrc){
  1120. [].forEach.call(eles, ele=>{
  1121. [].forEach.call(ele.querySelectorAll("img"), img=>{
  1122. if(img.getAttribute(lazyImgSrc)){
  1123. img.src=img.getAttribute(lazyImgSrc);
  1124. }
  1125. });
  1126. });
  1127. }
  1128. }
  1129.  
  1130. initPage(callback){
  1131. let self=this;
  1132. curPage=1;
  1133. //if(this.curSiteRule.url && !this.curSiteRule.singleUrl)return;
  1134. this.curSiteRule={};
  1135. this.pageDoc=document;
  1136. this.nextLinkHref=null;
  1137. this.curUrl=location.href;
  1138. this.getRule(()=>{
  1139. if(self.curSiteRule.enable==0){
  1140. debug("Stop as rule disable");
  1141. isPause=true;
  1142. return;
  1143. }
  1144. if(self.curSiteRule && !self.curSiteRule.singleUrl){
  1145. self.hpRules=self.hpRules.filter(item=>{return item&&item.url!=self.curSiteRule.url});
  1146. self.hpRules.unshift(self.curSiteRule);
  1147. if(self.hpRules.length>30){
  1148. self.hpRules.pop();
  1149. }
  1150. storage.setItem("hpRules", self.hpRules);
  1151. }
  1152. let css=self.curSiteRule.css;
  1153. if(css){
  1154. _GM_addStyle(css);
  1155. }
  1156. let code=self.curSiteRule.init;
  1157. if(code){
  1158. try{
  1159. Function('doc','"use strict";' + code)(null);
  1160. }catch(e){
  1161. debug(e);
  1162. }
  1163. }
  1164. self.getNextLink(document);
  1165. callback();
  1166. });
  1167. }
  1168.  
  1169. insertPage(doc, eles, url, callback, tried){
  1170. let oldUrl=this.curUrl;
  1171. let oldTitle=this.pageDoc.title;
  1172. this.pageDoc=doc;
  1173. this.curUrl=url;
  1174. let nextLink=this.getNextLink(doc);
  1175. if(curPage==1 && !tried && !this.nextLinkHref && this.curSiteRule.singleUrl && this.curSiteRule.pageElement && this.curSiteRule.pageElement!=allOfBody){
  1176. this.curSiteRule.action=1;
  1177. this.curUrl=location.href;
  1178. return false;
  1179. }
  1180. if(callback)callback(eles);
  1181. this.getInsert();
  1182. var self=this,newEles=[];
  1183. if(!eles || eles.length==0 || !self.insert || !self.insert.parentNode){
  1184. }else{
  1185. this.pageInit(doc, eles);
  1186. [].forEach.call(eles, ele=>{
  1187. let newEle=ele.cloneNode(true);
  1188. let oldCanvass=ele.querySelectorAll("canvas");
  1189. let newCanvass=newEle.querySelectorAll("canvas");
  1190. for(let i=0;i<oldCanvass.length;i++){
  1191. let oldCanvas=oldCanvass[i];
  1192. let newCanvas=newCanvass[i];
  1193. newCanvas.getContext('2d').drawImage(oldCanvas, 0, 0);
  1194. }
  1195. if(self.curSiteRule.insertPos==2){
  1196. self.insert.appendChild(newEle);
  1197. }else{
  1198. self.insert.parentNode.insertBefore(newEle, self.insert);
  1199. }
  1200. newEles.push(newEle);
  1201. });
  1202. }
  1203. this.pageAction(doc, newEles);
  1204. if(oldUrl!=location.href){
  1205. let isJs=/^(javascript|#)/.test(oldUrl.replace(location.href,""));
  1206. if(rulesData.enableHistory && !isJs){
  1207. _unsafeWindow.history.replaceState(undefined, oldTitle, oldUrl);
  1208. document.title=oldTitle;
  1209. }
  1210. }
  1211. return true;
  1212. }
  1213. }
  1214. var ruleParser = new RuleParser();
  1215.  
  1216. function initConfig(){
  1217. _GM_registerMenuCommand(i18n(forceState==1?"enable":"disableSite"), ()=>{
  1218. storage.setItem("forceState_"+location.host, (forceState==1?0:1));
  1219. location.reload();
  1220. });
  1221. _GM_registerMenuCommand(i18n("update"), ()=>{
  1222. updateRules(()=>{
  1223. alert(i18n("updateSucc"));
  1224. location.reload();
  1225. },(rule,err)=>{
  1226. alert("Update "+rule.url+" rules fail!");
  1227. });
  1228. alert(i18n("beginUpdate"));
  1229. });
  1230.  
  1231. var configCon,insertPos;
  1232. if(location.href==configPage){
  1233. _GM_addStyle(`
  1234. p>span:nth-child(1),p>span:nth-child(2),p>span:nth-child(3){
  1235. cursor: pointer;
  1236. user-select: none;
  1237. }
  1238. p>span:nth-child(1):hover,p>span:nth-child(2):hover,p>span:nth-child(3):hover{
  1239. color:red;
  1240. }
  1241. .updateDate{
  1242. cursor: pointer;
  1243. user-select: none;
  1244. }
  1245. .updateDate:hover{
  1246. color:red;
  1247. }
  1248. `);
  1249. configCon=document.querySelector(".markdown-body");
  1250. insertPos=configCon.querySelector("hr");
  1251. }else if(location.href==configPage){
  1252. }else return false;
  1253. class Rulebar {
  1254. init(ruleUrl){
  1255. this.ruleUrl=ruleUrl;
  1256. this.item=document.createElement("p");
  1257. this.item.title=ruleUrl.type==0?"AutoPagerize Rules":"Pagetual Rules";
  1258. this.item.dataset.id=this.ruleUrl.id;
  1259. let url=document.createElement("span");
  1260. url.innerHTML=ruleUrl.url;
  1261. let up=document.createElement("span");
  1262. up.innerHTML="↑ ";
  1263. up.title=i18n("sortTitle");
  1264. let down=document.createElement("span");
  1265. down.innerHTML="↓ ";
  1266. down.title=i18n("sortTitle");
  1267. let del=document.createElement("span");
  1268. del.innerHTML="× ";
  1269. up.onclick=e=>{
  1270. this.moveUp();
  1271. };
  1272. down.onclick=e=>{
  1273. this.moveDown();
  1274. };
  1275. del.onclick=e=>{
  1276. this.del();
  1277. };
  1278. this.item.appendChild(up);
  1279. this.item.appendChild(down);
  1280. this.item.appendChild(del);
  1281. this.item.appendChild(url);
  1282. configCon.insertBefore(this.item, insertPos);
  1283. }
  1284. saveSort(){
  1285. let sort=[];
  1286. [].forEach.call(this.item.parentNode.querySelectorAll("p[data-id]"), i=>{
  1287. sort.push(i.dataset.id);
  1288. });
  1289. rulesData.sort=sort;
  1290. storage.setItem("rulesData", rulesData);
  1291. }
  1292. moveUp(){
  1293. let preE=this.item.previousElementSibling;
  1294. if(preE.tagName=="P" && preE.children.length>1){
  1295. this.item.parentNode.insertBefore(this.item,preE);
  1296. this.saveSort();
  1297. }
  1298. }
  1299. moveDown(){
  1300. let nextE=this.item.nextElementSibling;
  1301. if(nextE.tagName=="P" && nextE.children.length>1){
  1302. this.item.parentNode.insertBefore(nextE,this.item);
  1303. this.saveSort();
  1304. }
  1305. }
  1306. del(){
  1307. if(this.ruleUrl.id<2){
  1308. alert(i18n("cantDel"));
  1309. }else if(window.confirm(i18n("confirmDel"))){
  1310. for(let u=0;u<rulesData.urls.length;u++){
  1311. if(this.ruleUrl.id==rulesData.urls[u].id){
  1312. rulesData.urls.splice(u,1);
  1313. break;
  1314. }
  1315. }
  1316. for(let u=0;u<rulesData.sort.length;u++){
  1317. if(this.ruleUrl.id==rulesData.sort[u]){
  1318. rulesData.sort.splice(u,1);
  1319. break;
  1320. }
  1321. }
  1322. storage.setItem("rulesData", rulesData);
  1323. ruleParser.rules=ruleParser.rules.filter(item=>{return item.from!=this.ruleUrl.id});
  1324. storage.setItem("rules", ruleParser.rules);
  1325. this.item.parentNode.removeChild(this.item);
  1326. //location.reload();
  1327. }
  1328. }
  1329. }
  1330. let updateP=document.createElement("p"),i=0;
  1331. let now=new Date().getTime(),inUpdate=false;
  1332.  
  1333.  
  1334. let pastDate=(new Date(updateDate)).toString(),passStr;
  1335. let passTime=(now-updateDate)/1000;
  1336. if(isNaN(passTime)){
  1337. passStr=i18n("firstUpdate");
  1338. }else if(passTime<60){
  1339. passStr=i18n("passSec", parseInt(passTime))+" ← "+i18n("click2update");
  1340. }else if(passTime<60*60){
  1341. passStr=i18n("passMin", parseInt(passTime/60))+" ← "+i18n("click2update");
  1342. }else if(passTime<60*60*24){
  1343. passStr=i18n("passHour", parseInt(passTime/3600))+" ← "+i18n("click2update");
  1344. }else{
  1345. passStr=i18n("passDay", parseInt(passTime/86400))+" ← "+i18n("click2update");
  1346. }
  1347.  
  1348.  
  1349. updateP.className="updateDate";
  1350. updateP.innerHTML=passStr;
  1351. updateP.title=i18n("update")+" - "+pastDate;
  1352. updateP.onclick=e=>{
  1353. updateRules(()=>{
  1354. alert(i18n("updateSucc"));
  1355. updateP.innerHTML=i18n("passSec", 0);
  1356. updateP.title=i18n("update");
  1357. },(rule,err)=>{
  1358. alert("Update "+rule.url+" rules fail!");
  1359. });
  1360. alert(i18n("beginUpdate"));
  1361. };
  1362. configCon.insertBefore(updateP, insertPos);
  1363. if(ruleUrls){
  1364. ruleUrls.forEach(ruleUrl=>{
  1365. var rulebar=new Rulebar();
  1366. rulebar.init(ruleUrl);
  1367. });
  1368. }
  1369. let customUrlsTitle=document.createElement("h2");
  1370. customUrlsTitle.innerHTML=i18n("customUrls");
  1371. configCon.insertBefore(customUrlsTitle, insertPos);
  1372. let customUrlsInput=document.createElement("textarea");
  1373. customUrlsInput.style.width="100%";
  1374. customUrlsInput.placeholder="0|http://wedata.net/databases/AutoPagerize/items_all.json";
  1375. configCon.insertBefore(customUrlsInput, insertPos);
  1376.  
  1377. let opacityTitle=document.createElement("h2");
  1378. opacityTitle.innerHTML=i18n("opacity");
  1379. let opacityInput=document.createElement("input");
  1380. opacityInput.value=rulesData.opacity*100;
  1381. opacityInput.type="number";
  1382. opacityInput.style.width="50px";
  1383. opacityInput.style.margin="0 0 0 10px";
  1384. opacityTitle.appendChild(opacityInput);
  1385. configCon.insertBefore(opacityTitle, insertPos);
  1386.  
  1387. function createCheckbox(innerText, val){
  1388. let title=document.createElement("h2");
  1389. title.innerHTML=innerText;
  1390. let input=document.createElement("input");
  1391. input.type="checkbox";
  1392. input.style.width="50px";
  1393. input.style.height="20px";
  1394. input.checked=val;
  1395. title.appendChild(input);
  1396. configCon.insertBefore(title, insertPos);
  1397. return input;
  1398. }
  1399.  
  1400. let hideBarInput=createCheckbox(i18n("hideBar"), rulesData.hideBar);
  1401. let dbClick2StopInput=createCheckbox(i18n("dbClick2Stop"), rulesData.dbClick2Stop);
  1402. let enableWhiteListInput=createCheckbox(i18n("autoRun"), rulesData.enableWhiteList!=true);
  1403. let enableDebugInput=createCheckbox(i18n("enableDebug"), rulesData.enableDebug!=false);
  1404. let enableHistoryInput=createCheckbox(i18n("enableHistory"), rulesData.enableHistory!=false);
  1405.  
  1406. let customRulesTitle=document.createElement("h2");
  1407. customRulesTitle.innerHTML=i18n("customRules")
  1408. configCon.insertBefore(customRulesTitle, insertPos);
  1409. let customRulesInput=document.createElement("textarea");
  1410. customRulesInput.style.width="100%";
  1411. customRulesInput.style.height="500px";
  1412. 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]`;
  1413. customRulesInput.value=getFormatJSON(ruleParser.customRules);
  1414. configCon.insertBefore(customRulesInput, insertPos);
  1415. let saveBtn=document.createElement("button");
  1416. saveBtn.innerHTML=i18n("save");
  1417. saveBtn.style.width="100%";
  1418. configCon.insertBefore(saveBtn, insertPos);
  1419. saveBtn.onclick=e=>{
  1420. try{
  1421. storage.setItem("hpRules", []);
  1422. if(customRulesInput.value==""){
  1423. storage.setItem("customRules", "");
  1424. }else{
  1425. let customRules=JSON.parse(customRulesInput.value);
  1426. if(Array && Array.isArray && !Array.isArray(customRules)){
  1427. alert("Rules must be a Array!");
  1428. return;
  1429. }
  1430. debug(customRules);
  1431. storage.setItem("customRules", customRules);
  1432. }
  1433. }catch(e){
  1434. debug(e);
  1435. alert("JSON error, check again!");
  1436. return;
  1437. }
  1438. rulesData.opacity=opacityInput.value/100;
  1439. rulesData.hideBar=hideBarInput.checked;
  1440. rulesData.dbClick2Stop=dbClick2StopInput.checked;
  1441. rulesData.enableWhiteList=!enableWhiteListInput.checked;
  1442. rulesData.enableDebug=enableDebugInput.checked;
  1443. rulesData.enableHistory=enableHistoryInput.checked;
  1444. storage.setItem("rulesData", rulesData);
  1445. let customUrls=customUrlsInput.value.trim();
  1446. if(customUrls){
  1447. customUrls=customUrls.split(/\n/);
  1448. for(let c=0;c<customUrls.length;c++){
  1449. let urlArr=customUrls[c].split("|"),url,type=1;
  1450. if(urlArr.length==1){
  1451. url=urlArr[0].trim();
  1452. if(!/^http/.test(url)){
  1453. alert("Wrong url, check again!");
  1454. return;
  1455. }
  1456. }else if(urlArr.length==2){
  1457. type=urlArr[0].trim();
  1458. url=urlArr[1].trim();
  1459. if(!/^http/.test(url)){
  1460. alert("Wrong url, check again!");
  1461. return;
  1462. }
  1463. }else{
  1464. break;
  1465. }
  1466. let maxId=0,hasUrl=false;
  1467. if(!rulesData.urls){
  1468. rulesData.urls=[];
  1469. maxId=1;
  1470. }else{
  1471. rulesData.urls.forEach(u=>{
  1472. if(maxId<u.id){
  1473. maxId=u.id;
  1474. }
  1475. if(u.url==url){
  1476. hasUrl=true;
  1477. }
  1478. });
  1479. if(hasUrl)break;
  1480. }
  1481. rulesData.urls.push({id:maxId+1,url:url,type:type});
  1482. rulesData.sort.push(maxId+1);
  1483. storage.setItem("rulesData", rulesData);
  1484. }
  1485. }
  1486. alert("Modified successfully");
  1487. location.reload();
  1488. };
  1489. return true;
  1490. }
  1491.  
  1492. var inUpdate=false;
  1493. function updateRules(success,fail){
  1494. if(inUpdate)return;
  1495. inUpdate=true;
  1496. let ruleIndex=ruleUrls.length-1;
  1497. storage.setItem("hpRules", []);
  1498. function addNextRule(){
  1499. if(ruleIndex<0){
  1500. let now=new Date().getTime();
  1501. storage.setItem("ruleLastUpdate", now);
  1502. storage.setItem("rules", ruleParser.rules);
  1503. inUpdate=false;
  1504. success();
  1505. }else{
  1506. let rule=ruleUrls[ruleIndex--];
  1507. ruleParser.addRuleByUrl(rule.url, rule.type, rule.id, (json,err)=>{
  1508. if(!json){
  1509. fail(rule,err);
  1510. }
  1511. storage.setItem("rules", ruleParser.rules);
  1512. addNextRule();
  1513. })
  1514. }
  1515. }
  1516. addNextRule();
  1517. }
  1518.  
  1519. function objIsArr(obj) {
  1520. return obj &&
  1521. typeof obj === 'object' &&
  1522. typeof obj.length === 'number' &&
  1523. !(obj.propertyIsEnumerable('length'));
  1524. }
  1525.  
  1526. function isVisible(el, win) {
  1527. if(!el.offsetParent)return false;
  1528. var loopable = true,
  1529. visible = el.tagName && win.getComputedStyle(el).display != 'none' && win.getComputedStyle(el).visibility != 'hidden';
  1530. while(loopable && visible) {
  1531. el = el.parentNode;
  1532.  
  1533. if(el && el.tagName && el.tagName!="BODY") {
  1534. visible = win.getComputedStyle(el).display != 'none' && win.getComputedStyle(el).visibility != 'hidden';
  1535. }else {
  1536. loopable = false;
  1537. }
  1538. }
  1539. return visible;
  1540. }
  1541.  
  1542. function getFormatJSON(obj){
  1543. if(!objIsArr(obj))return "";
  1544. let ret="[\n";
  1545. let len=obj.length,i=0,isLast;
  1546. obj.forEach(item=>{
  1547. ret+=" {\n";
  1548. let iLen=Object.keys(item).length,j=0;
  1549. for(let key in item){
  1550. isLast=(++j)==iLen;
  1551. let value=item[key];
  1552. if(objIsArr(value)){
  1553. let vstr="[",v=0,vIsLast=false;
  1554. value.forEach(vi=>{
  1555. vIsLast=(++v)==value.length;
  1556. vstr+="\""+vi.replace(/\\/g,"\\\\")+"\""+(vIsLast?"":",");
  1557. });
  1558. vstr+="]";
  1559. ret+=" \""+key+"\":"+vstr+""+(isLast?"":",")+"\n";
  1560. }else{
  1561. if(typeof value=="string"){
  1562. value=value.replace(/\\/g,"\\\\").replace(/"/g,"\\\"");
  1563. value="\""+value+"\"";
  1564. }
  1565. ret+=" \""+key+"\":"+value+""+(isLast?"":",")+"\n";
  1566. }
  1567. }
  1568. isLast=(++i)==len;
  1569. ret+=" }"+(isLast?"":",")+"\n";
  1570. });
  1571. ret+="]";
  1572. return ret;
  1573. }
  1574.  
  1575. function initRules(callback) {
  1576. /*0 wedata格式,1 pagetual格式*/
  1577. ruleUrls=[
  1578. {
  1579. id:0,
  1580. url:'https://raw.githubusercontent.com/hoothin/UserScripts/master/Pagetual/pagetualRules.json',
  1581. type:1
  1582. },
  1583. {
  1584. id:1,
  1585. url:'http://wedata.net/databases/AutoPagerize/items_all.json',
  1586. type:0,
  1587. }
  1588. ];var i=0,j=0;
  1589.  
  1590. ruleParser.initSavedRules(()=>{
  1591. storage.getItem("rulesData", data=>{
  1592. if(data){
  1593. rulesData=data;
  1594. if(data.urls)ruleUrls=ruleUrls.concat(data.urls);
  1595. if(data.sort){
  1596. let urls=[];
  1597. data.sort.forEach(id=>{
  1598. for(let s=0;s<ruleUrls.length;s++){
  1599. if(id==ruleUrls[s].id){
  1600. urls.push(ruleUrls[s]);
  1601. break;
  1602. }
  1603. }
  1604. });
  1605. ruleUrls=urls;
  1606. }
  1607. }
  1608. if(typeof(rulesData.opacity)=="undefined"){
  1609. rulesData.opacity=0.3;
  1610. }
  1611. if(typeof(rulesData.hideBar)=="undefined"){
  1612. rulesData.hideBar=true;
  1613. }
  1614. if(typeof(rulesData.dbClick2Stop)=="undefined"){
  1615. rulesData.dbClick2Stop=true;
  1616. }
  1617. if(typeof(rulesData.enableWhiteList)=="undefined"){
  1618. rulesData.enableWhiteList=false;
  1619. }
  1620. if(typeof(rulesData.enableHistory)=="undefined"){
  1621. rulesData.enableHistory=true;
  1622. }
  1623. if(typeof(rulesData.enableDebug)=="undefined"){
  1624. rulesData.enableDebug=true;
  1625. }
  1626. enableDebug=rulesData.enableDebug;
  1627. storage.getItem("forceState_"+location.host, v=>{
  1628. storage.getItem("ruleLastUpdate", date=>{
  1629. if(typeof(v)=="undefined"){
  1630. v=(rulesData.enableWhiteList?1:0);
  1631. }
  1632. forceState=v;
  1633. updateDate=date;
  1634. if(initConfig())return;
  1635. if(forceState==1)return;
  1636. let now=new Date().getTime();
  1637. if(!date || now-date>2*24*60*60*1000){
  1638. storage.setItem("ruleLastUpdate", now);
  1639. updateRules(()=>{
  1640. callback();
  1641. },(rule,err)=>{});
  1642. }else{
  1643. callback();
  1644. }
  1645. });
  1646. });
  1647. });
  1648. });
  1649. }
  1650.  
  1651. function requestDoc(url, callback){
  1652. _GM_xmlhttpRequest({
  1653. url: url,
  1654. method: 'GET',
  1655. overrideMimeType: 'text/html;charset='+document.charset,
  1656. headers: {
  1657. 'Referer': location.href
  1658. },
  1659. timeout: 5000,
  1660. onload: function(res) {
  1661. var doc=null;
  1662. try {
  1663. doc=document.implementation.createHTMLDocument('');
  1664. doc.documentElement.innerHTML=res.response;
  1665. }
  1666. catch (e) {
  1667. debug('parse error'+e.toString());
  1668. }
  1669. let pageElement=ruleParser.getPageElement(doc);
  1670. //只有1的話怕不是圖片哦
  1671. if(pageElement && (pageElement.length>1 || (pageElement.length==1 && pageElement[0].tagName!="IMG") )){
  1672. let result=ruleParser.insertPage(doc, pageElement, url, callback, false);
  1673. if(!result){
  1674. requestFromIframe(url, (doc, eles)=>{
  1675. loadPageOver();
  1676. if(eles){
  1677. ruleParser.insertPage(doc, eles, url, callback, true);
  1678. }
  1679. });
  1680. }
  1681. }else if(ruleParser.curSiteRule.singleUrl){
  1682. requestFromIframe(url, (doc, eles)=>{
  1683. loadPageOver();
  1684. if(eles){
  1685. ruleParser.insertPage(doc, eles, url, callback, true);
  1686. }
  1687. });
  1688. }else{
  1689. isPause=true;
  1690. callback(false);
  1691. }
  1692. },
  1693. onerror: function(e){
  1694. debug(e);
  1695. callback(false);
  1696. },
  1697. ontimeout: function(e){
  1698. debug(e);
  1699. callback(false);
  1700. }
  1701. });
  1702. }
  1703.  
  1704. var failFromIframe=0;
  1705. function requestFromIframe(url, callback){
  1706. let orgPage,curPage;
  1707. let iframe = document.createElement('iframe');
  1708. iframe.name = 'pagetual-iframe';
  1709. iframe.width = '100%';
  1710. iframe.height = '0';
  1711. iframe.frameBorder = '0';
  1712. if(ruleParser.curSiteRule.sandbox!=false){
  1713. iframe.sandbox="allow-same-origin allow-scripts allow-popups allow-forms";
  1714. }
  1715. iframe.style.cssText = 'margin:0!important;padding:0!important;visibility:hidden!important;';
  1716. iframe.addEventListener("load", e=>{
  1717. let waitTime=500,checkEval;
  1718. if(ruleParser.curSiteRule.wait){
  1719. if(isNaN(ruleParser.curSiteRule.wait)){
  1720. try{
  1721. checkEval=Function("doc",'"use strict";' + ruleParser.curSiteRule.wait);
  1722. }catch(e){
  1723. debug(e);
  1724. }
  1725. }else{
  1726. waitTime=ruleParser.curSiteRule.wait;
  1727. }
  1728. }
  1729. setTimeout(()=>{
  1730. let tryTimes=0;
  1731. function checkIframe(){
  1732. try{
  1733. let doc=iframe.contentDocument || iframe.contentWindow.document;
  1734. let eles=ruleParser.getPageElement(doc, iframe.contentWindow);
  1735. if(eles && eles.length>0 && (!checkEval || checkEval(doc))){
  1736. callback(doc, eles);
  1737. }else if(tryTimes++ < 10){
  1738. setTimeout(()=>{
  1739. checkIframe();
  1740. },waitTime);
  1741. return;
  1742. }else{
  1743. if(failFromIframe++ > 2){
  1744. failFromIframe=0;
  1745. debug("Stop as failFromIframe");
  1746. isPause=true;
  1747. callback(false, false);
  1748. }else{
  1749. callback(false, false);
  1750. }
  1751. }
  1752. }catch(e){
  1753. debug("Stop as cors");
  1754. //isPause=true;
  1755. ruleParser.curSiteRule.pageElement=allOfBody;
  1756. ruleParser.getInsert(true);
  1757. callback(false, false);
  1758. }
  1759. document.body.removeChild(iframe);
  1760. }
  1761. checkIframe();
  1762. },waitTime);
  1763. });
  1764. iframe.src=url;
  1765. document.body.appendChild(iframe);
  1766. }
  1767.  
  1768. function initPage(){
  1769. ruleParser.initPage(()=>{
  1770. if(ruleParser.nextLinkHref){
  1771. initView();
  1772. let isJs=/^(javascript|#)/.test(ruleParser.nextLinkHref.replace(location.href,""));
  1773. if(!isJs){
  1774. _GM_registerMenuCommand(i18n(forceState==2?"cancelForceIframe":"forceIframe"), ()=>{
  1775. storage.setItem("forceState_"+location.host, (forceState==2?"":2));
  1776. location.reload();
  1777. });
  1778. }
  1779. _GM_registerMenuCommand(i18n("loadNow"), ()=>{
  1780. let loadNum=window.prompt(i18n("loadConfirm"), "1");
  1781. if(loadNum==="" || loadNum===null)return;
  1782. autoLoadNum=Math.abs(parseInt(loadNum));
  1783. nextPage();
  1784. });
  1785. }
  1786. initListener();
  1787. nextPage();
  1788. });
  1789. }
  1790.  
  1791. function initView(){
  1792. _GM_addStyle(`
  1793. .pagetual_pageBar.stop {
  1794. -webkit-filter: invert(100%);
  1795. filter: invert(100%);
  1796. opacity: 1!important;
  1797. }
  1798. .pagetual_pageBar.hide {
  1799. display: none!important;
  1800. }
  1801. .pagetual_pageBar:hover {
  1802. opacity: 1!important;
  1803. }
  1804. .pagetual_pageBar span {
  1805. vertical-align: super;
  1806. }
  1807.  
  1808. .pagetual_pageBar span>svg:hover {
  1809. animation: touhouAni 1s infinite;
  1810. }
  1811. .pagetual_pageBar .pagetual_pageNum{
  1812. color: #55555f;
  1813. }
  1814. .pagetual_pageBar .pagetual_pageNum:hover{
  1815. color: #ff6464;
  1816. }
  1817.  
  1818. @keyframes touhouAni{
  1819. from {transform: rotate(0deg) scale3d(1.2, 1.2, 1.2);}
  1820. to {transform: rotate(360deg);}
  1821. }
  1822. @-webkit-keyframes touhouAni{
  1823. from {transform: rotate(0deg) scale3d(1.2, 1.2, 1.2);}
  1824. to {transform: rotate(360deg);}
  1825. }
  1826. `);
  1827. 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;`;
  1828. }
  1829. var loadingDiv=document.createElement("div");
  1830. loadingDiv.className="pagetual_loading";
  1831. 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;";
  1832. 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>`;
  1833.  
  1834. 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>`;
  1835. 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>`;
  1836. var pageBarStyle;
  1837. 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;`;
  1838. 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);`;
  1839.  
  1840. var isPause=false,isLoading=false,curPage=1,forceState=0,bottomGap=1000,autoLoadNum=-1;
  1841.  
  1842. function changeStop(stop, hide){
  1843. isPause=stop;
  1844. [].forEach.call(document.querySelectorAll(".pagetual_pageBar"), bar=>{
  1845. if(isPause){
  1846. bar.classList.add("stop");
  1847. if(hide)bar.classList.add("hide");
  1848. }else{
  1849. bar.classList.remove("stop");
  1850. if(hide)bar.classList.remove("hide");
  1851. }
  1852. });
  1853. }
  1854.  
  1855. function isInViewPort(element) {
  1856. if(!element.parentNode)return false;
  1857. if(_unsafeWindow.getComputedStyle(element).display=="none")return false;
  1858. const viewWidth = window.innerWidth || document.documentElement.clientWidth;
  1859. const viewHeight = window.innerHeight || document.documentElement.clientHeight;
  1860. const {
  1861. top,
  1862. right,
  1863. bottom,
  1864. left,
  1865. } = element.getBoundingClientRect();
  1866.  
  1867. return (
  1868. top >= 0 &&
  1869. left >= 0 &&
  1870. right <= viewWidth &&
  1871. bottom <= viewHeight
  1872. );
  1873. }
  1874.  
  1875. var urlChanged=false;
  1876. var _wr = function(type) {
  1877. var orig = history[type];
  1878. return function() {
  1879. var rv = orig.apply(this, arguments);
  1880. var e = new Event(type);
  1881. e.arguments = arguments;
  1882. window.dispatchEvent(e);
  1883. return rv;
  1884. };
  1885. };
  1886. history.pushState = _wr('pushState');
  1887. window.addEventListener('pushState', function(e) {
  1888. urlChanged=true;
  1889. isPause=true;
  1890. setTimeout(()=>{
  1891. if(location.href==configPage){
  1892. location.reload();
  1893. }
  1894. },1);
  1895. });
  1896.  
  1897. function initListener(){
  1898. let loadmoreBtn,loading=true;
  1899. setTimeout(()=>{
  1900. loadmoreBtn=getLoadMore(document);
  1901. if(loadmoreBtn && isVisible(loadmoreBtn, _unsafeWindow)){
  1902. loading=false;
  1903. }
  1904. },500);
  1905. let checkScrollReach=()=>{
  1906. let scrolly=window.scrollY;
  1907. let windowHeight=window.innerHeight || document.documentElement.clientHeight;
  1908. let scrollH=Math.max(document.documentElement.scrollHeight, document.body.scrollHeight);
  1909. if(scrollH-scrolly-windowHeight<bottomGap){
  1910. nextPage();
  1911. }
  1912. };
  1913. document.addEventListener('scroll', e=>{
  1914. if(urlChanged){
  1915. ruleParser.initPage(()=>{
  1916. if(ruleParser.nextLinkHref)initView();
  1917. });
  1918. urlChanged=false;
  1919. isPause=false;
  1920. }
  1921. if(isPause)return;
  1922. if(!loading){
  1923. loading=true;
  1924. setTimeout(()=>{loading=false},200);
  1925. if(!loadmoreBtn || !loadmoreBtn.parentNode){
  1926. loadmoreBtn=getLoadMore(document);
  1927. }
  1928. if(loadmoreBtn){
  1929. if(isInViewPort(loadmoreBtn)){
  1930. emuClick(loadmoreBtn);
  1931. }
  1932. }
  1933. }
  1934. setTimeout(()=>{
  1935. if(!isLoading){
  1936. checkScrollReach();
  1937. }
  1938. },100);
  1939. }, true);
  1940. document.addEventListener('dblclick', e=>{
  1941. if(rulesData.dbClick2Stop){
  1942. setTimeout(()=>{
  1943. changeStop(!isPause, rulesData.hideBar);
  1944. if(!isPause){
  1945. checkScrollReach();
  1946. }
  1947. },200);
  1948. }
  1949. });
  1950. }
  1951.  
  1952. function getLoadMore(doc){
  1953. if(ruleParser.curSiteRule.loadMore==="")return null;
  1954. let btnSel=ruleParser.curSiteRule.loadMore||".LoadMore,.load-more";
  1955. let loadmoreBtn=doc.querySelector(btnSel);
  1956. if(!loadmoreBtn){
  1957. let buttons=doc.querySelectorAll("input,button,a,div[onclick]"),loadmoreReg=/^\s*(加载更多|加載更多|load\s*more|もっと読み込む)\s*$/i;
  1958. for(let i=0;i<buttons.length;i++){
  1959. let button=buttons[i];
  1960. if(button && loadmoreReg.test(button.innerText)){
  1961. loadmoreBtn=button;
  1962. break;
  1963. }
  1964. }
  1965. }
  1966. return loadmoreBtn;
  1967. }
  1968.  
  1969. var hasPageNum=true;
  1970. function createPageBar(url){
  1971. let insert=ruleParser.getInsert();
  1972. if(!insert || !insert.parentNode)return;
  1973. curPage++;
  1974. if(rulesData.opacity==0)return;
  1975. let example=ruleParser.curSiteRule.insertPos==2?insert.children[0]:(insert.previousElementSibling||insert);
  1976. let inTable=example.parentNode.tagName=="TABLE" ||
  1977. example.tagName=="TR" ||
  1978. example.tagName=="TBODY" ||
  1979. (example.previousElementSibling && example.previousElementSibling.tagName=="TR") ||
  1980. (example.previousElementSibling && example.previousElementSibling.tagName=="TBODY");
  1981. let inLi=example.tagName=="LI" || (example.previousElementSibling && example.previousElementSibling.tagName=="LI");
  1982. let pageBar=document.createElement(inTable?"tr":(inLi?"li":"div"));
  1983. let upSpan=document.createElement("span");
  1984. let downSpan=document.createElement("span");
  1985. let pageText=document.createElement("a");
  1986. let pageNum;
  1987. pageBar.className="pagetual_pageBar";
  1988. pageBar.id="pagetual_pageBar";
  1989. if(isPause){
  1990. pageBar.classList.add("stop");
  1991. }
  1992. pageBar.style.cssText=pageBarStyle;
  1993. pageBar.title=i18n(isPause?"enable":"disable");
  1994. upSpan.innerHTML=upSvg;
  1995. upSpan.title=i18n("toTop");
  1996. downSpan.innerHTML=downSvg;
  1997. downSpan.title=i18n("toBottom");
  1998. upSpan.style.cssText=initStyle;
  1999. downSpan.style.cssText=initStyle;
  2000. pageText.href=url;
  2001. pageText.style.cssText=pageTextStyle;
  2002. pageText.title=i18n("current");
  2003. pageBar.appendChild(upSpan);
  2004. pageBar.appendChild(pageText);
  2005. if(ruleParser.curSiteRule.pageNum || (hasPageNum && /[&\/\?](p=|page[=\/])\d+/.test(url))){
  2006. pageText.innerHTML="Page ";
  2007. pageNum=document.createElement("span");
  2008. pageNum.innerText=curPage;
  2009. pageNum.className="pagetual_pageNum";
  2010. pageNum.title=i18n("inputPageNum");
  2011. pageNum.style.cssText=pageTextStyle;
  2012. pageNum.style.cursor="pointer";
  2013. pageNum.style.color="";
  2014. pageNum.addEventListener("click", e=>{
  2015. let pageInput=prompt(i18n("inputPageNum"));
  2016. if(pageInput){
  2017. let pageLink=ruleParser.getLinkByPage(url, pageInput);
  2018. if(pageLink){
  2019. _GM_openInTab(pageLink,{active:true});
  2020. }
  2021. }
  2022. e.preventDefault();
  2023. e.stopPropagation();
  2024. });
  2025. pageBar.appendChild(pageNum);
  2026. }else{
  2027. pageText.innerHTML="Page "+curPage;
  2028. hasPageNum=false;
  2029. }
  2030. pageBar.appendChild(downSpan);
  2031. let parentStyle=_unsafeWindow.getComputedStyle(example.parentNode);
  2032. pageBar.style.width=parentStyle.width;
  2033. if(parentStyle.display=="grid" || parentStyle.display=="inline-grid"){
  2034. pageBar.style.gridColumnStart=1;
  2035. pageBar.style.gridColumnEnd=1+parseInt(example.parentNode.offsetWidth/example.offsetWidth);
  2036. }
  2037. if(inTable){
  2038. example=(example.tagName=="TR" || example.tagName=="TBODY")?example:example.previousElementSibling;
  2039. if(example.previousElementSibling)example=example.previousElementSibling;
  2040. let tdNum=0;
  2041. [].forEach.call(example.querySelectorAll("td,th"), td=>{
  2042. tdNum+=td.colSpan||1;
  2043. });
  2044. pageBar.style.display="table-row";
  2045. pageBar.style.backgroundColor="unset";
  2046. let td=document.createElement("td");
  2047. td.style.backgroundColor="rgb(240 240 240 / 80%)";
  2048. td.style.borderRadius="20px";
  2049. td.colSpan=tdNum||1;
  2050. td.style.padding="0 0";
  2051. td.style.textAlign="center";
  2052. td.appendChild(upSpan);
  2053. td.appendChild(pageText);
  2054. if(pageNum)td.appendChild(pageNum);
  2055. td.appendChild(downSpan);
  2056. pageBar.appendChild(td);
  2057. }else if(inLi){
  2058. example=example.tagName=="LI"?example:example.previousElementSibling;
  2059. pageBar.style.display="table-row";
  2060. pageBar.style.backgroundColor="unset";
  2061. let td=document.createElement("td");
  2062. td.style.backgroundColor="rgb(240 240 240 / 80%)";
  2063. td.style.borderRadius="20px";
  2064. td.colSpan=example.children.length;
  2065. td.style.padding="0 0";
  2066. td.style.textAlign="center";
  2067. td.style.minWidth="150px";
  2068. td.appendChild(upSpan);
  2069. td.appendChild(pageText);
  2070. td.style.width=pageBar.style.width;
  2071. if(pageNum)td.appendChild(pageNum);
  2072. td.appendChild(downSpan);
  2073. pageBar.appendChild(td);
  2074. }
  2075.  
  2076. upSpan.addEventListener("click", e=>{
  2077. document.body.scrollTop=0;
  2078. document.documentElement.scrollTop=0;
  2079. e.preventDefault();
  2080. e.stopPropagation();
  2081. });
  2082. downSpan.addEventListener("click", e=>{
  2083. changeStop(true);
  2084. pageBar.title=i18n(isPause?"enable":"disable");
  2085. document.body.scrollTop=9999999;
  2086. document.documentElement.scrollTop=9999999;
  2087. e.preventDefault();
  2088. e.stopPropagation();
  2089. });
  2090. pageBar.addEventListener("click", e=>{
  2091. changeStop(!isPause);
  2092. pageBar.title=i18n(isPause?"enable":"disable");
  2093. });
  2094. pageText.addEventListener("click", e=>{
  2095. e.stopPropagation();
  2096. });
  2097. if(ruleParser.curSiteRule.insertPos==2){
  2098. insert.appendChild(pageBar);
  2099. }else{
  2100. insert.parentNode.insertBefore(pageBar, insert);
  2101. }
  2102. if(ruleParser.curSiteRule.pageBar){
  2103. try{
  2104. Function("pageBar",'"use strict";' + ruleParser.curSiteRule.pageBar)(pageBar);
  2105. }catch(e){
  2106. debug(e);
  2107. }
  2108. }
  2109.  
  2110. let scrollH=Math.max(document.documentElement.scrollHeight, document.body.scrollHeight);
  2111. let posEle=pageBar.nextElementSibling||pageBar;
  2112. while(posEle && !posEle.offsetParent){
  2113. posEle=posEle.previousElementSibling||posEle.parentNode;
  2114. }
  2115. if(posEle){
  2116. let actualTop = posEle.offsetTop;
  2117. let current = posEle.parentNode.offsetParent;
  2118. while (current !== null){
  2119. actualTop += current.offsetTop;
  2120. current = current.offsetParent;
  2121. }
  2122. bottomGap=scrollH-actualTop+(window.innerHeight||document.documentElement.clientHeight)*(ruleParser.curSiteRule.rate||1);
  2123. }else{
  2124. bottomGap=1000;
  2125. }
  2126. return pageBar;
  2127. }
  2128.  
  2129. function emuClick(btn){
  2130. if(!PointerEvent)return btn.click();
  2131. let eventParam={
  2132. isTrusted: true,
  2133. altKey: false,
  2134. azimuthAngle: 0,
  2135. bubbles: true,
  2136. button: 0,
  2137. buttons: 0,
  2138. clientX: 1,
  2139. clientY: 1,
  2140. cancelBubble: false,
  2141. cancelable: true,
  2142. composed: true,
  2143. ctrlKey: false,
  2144. defaultPrevented: false,
  2145. detail: 1,
  2146. eventPhase: 2,
  2147. fromElement: null,
  2148. height: 1,
  2149. isPrimary: false,
  2150. metaKey: false,
  2151. pointerId: 1,
  2152. pointerType: "mouse",
  2153. pressure: 0,
  2154. relatedTarget: null,
  2155. returnValue: true,
  2156. shiftKey: false,
  2157. toElement: null,
  2158. twist: 0,
  2159. type: "click",
  2160. which: 1
  2161. };
  2162. var mouseclick = new PointerEvent("click",eventParam);
  2163. btn.dispatchEvent(mouseclick);
  2164. }
  2165.  
  2166. var emuIframe;
  2167. function emuPage(callback){
  2168. let orgPage,curPage,iframeDoc,times=0,loadmoreBtn,loadmoreEnd=false,waitTimes=10;
  2169. function checkPage(){
  2170. if(isPause)return;
  2171. try{
  2172. iframeDoc=emuIframe.contentDocument || emuIframe.contentWindow.document;
  2173. }catch(e){
  2174. debug("Stop as cors");
  2175. isPause=true;
  2176. callback(false, false);
  2177. return;
  2178. }
  2179.  
  2180. let nextLink=ruleParser.getNextLink(iframeDoc);
  2181. let waitTime=500,checkEval;
  2182. if(ruleParser.curSiteRule.wait){
  2183. if(isNaN(ruleParser.curSiteRule.wait)){
  2184. try{
  2185. checkEval=Function("doc",'"use strict";' + ruleParser.curSiteRule.wait);
  2186. }catch(e){
  2187. debug(e);
  2188. }
  2189. }else{
  2190. waitTime=ruleParser.curSiteRule.wait;
  2191. }
  2192. }
  2193.  
  2194. if(!orgPage){
  2195. if(!loadmoreEnd){
  2196. loadmoreBtn=getLoadMore(iframeDoc);
  2197. if(loadmoreBtn && isVisible(loadmoreBtn, iframeDoc.defaultView)){
  2198. emuClick(loadmoreBtn);
  2199. let intv=setInterval(()=>{
  2200. loadmoreBtn=getLoadMore(iframeDoc);
  2201. if(!loadmoreBtn || !loadmoreBtn.parentNode || !isVisible(loadmoreBtn, iframeDoc.defaultView)){
  2202. clearInterval(intv);
  2203. loadmoreEnd=true;
  2204. setTimeout(()=>{
  2205. checkPage();
  2206. },500);
  2207. }else{
  2208. emuClick(loadmoreBtn);
  2209. }
  2210. },200);
  2211. return;
  2212. }else{
  2213. loadmoreEnd=true;
  2214. }
  2215. }
  2216. let pageEle=ruleParser.getPageElement(iframeDoc, iframeDoc.defaultView, true);
  2217. if(!nextLink || !pageEle || (checkEval && !checkEval(iframeDoc))){
  2218. if(ruleParser.curSiteRule.wait && waitTimes-->0){
  2219. setTimeout(()=>{
  2220. checkPage();
  2221. },waitTime);
  2222. return;
  2223. }
  2224. }
  2225. orgPage=pageEle;
  2226. if(!orgPage || orgPage.length==0){
  2227. debug("Stop as no page when emu");
  2228. isPause=true;
  2229. callback(false, false);
  2230. return;
  2231. }
  2232. if(orgPage && orgPage[0].tagName=="UL")orgPage=orgPage[0].children;
  2233. if(orgPage && nextLink){
  2234. orgPage=orgPage[parseInt(orgPage.length/2)];
  2235. if(!isVisible(nextLink, iframeDoc.defaultView)){
  2236. debug("Stop as next hide when emu");
  2237. isPause=true;
  2238. callback(false, false);
  2239. }else{
  2240. emuClick(nextLink);
  2241. setTimeout(()=>{
  2242. checkPage();
  2243. },500);
  2244. }
  2245. }else{
  2246. debug("Stop as no next when emu");
  2247. isPause=true;
  2248. callback(false, false);
  2249. }
  2250. return;
  2251. }
  2252. if(times++ > 20){
  2253. //emuClick(nextLink);
  2254. debug("Stop as timeout when emu");
  2255. isPause=true;
  2256. callback(false, false);
  2257. return;
  2258. }
  2259. let eles=ruleParser.getPageElement(iframeDoc, iframeDoc.defaultView, true),checkItem=eles;
  2260. if(eles && eles.length>0 && eles[0].tagName=="UL")checkItem=eles[0].children;
  2261. if(!eles || eles.length==0 || orgPage == checkItem[parseInt(checkItem.length/2)] || (checkEval && !checkEval(iframeDoc))){
  2262. setTimeout(()=>{
  2263. checkPage();
  2264. },waitTime);
  2265. }else{
  2266. callback(iframeDoc, eles);
  2267. }
  2268. }
  2269. if(!emuIframe){
  2270. emuIframe = document.createElement('iframe');
  2271. emuIframe.name = 'pagetual-iframe';
  2272. if(ruleParser.curSiteRule.sandbox!=false){
  2273. emuIframe.sandbox="allow-same-origin allow-scripts allow-popups allow-forms";
  2274. }
  2275. emuIframe.width = '100%';
  2276. emuIframe.height = '0';
  2277. emuIframe.frameBorder = '0';
  2278. emuIframe.style.cssText = 'margin:0!important;padding:0!important;visibility:hidden!important;';
  2279. emuIframe.addEventListener("load", e=>{
  2280. setTimeout(()=>{
  2281. try{
  2282. iframeDoc=emuIframe.contentDocument || emuIframe.contentWindow.document;
  2283. }catch(e){
  2284. debug("Stop as cors");
  2285. isPause=true;
  2286. callback(false, false);
  2287. return;
  2288. }
  2289. let code=ruleParser.curSiteRule.init;
  2290. if(code){
  2291. try{
  2292. Function('doc','"use strict";' + code)(iframeDoc);
  2293. }catch(e){
  2294. debug(e);
  2295. }
  2296. }
  2297. checkPage();
  2298. },500);
  2299. });
  2300. emuIframe.src=location.href;
  2301. document.body.appendChild(emuIframe);
  2302. }else{
  2303. checkPage();
  2304. }
  2305. }
  2306.  
  2307. function forceIframe(url, callback){
  2308. let curIframe = document.createElement('iframe'),iframeDoc;
  2309. curIframe.name = 'pagetual-iframe';
  2310. curIframe.sandbox="allow-same-origin allow-scripts allow-popups allow-forms";
  2311. curIframe.frameBorder = '0';
  2312. curIframe.scrolling="no";
  2313. 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;';
  2314. curIframe.addEventListener("load", e=>{
  2315. try{
  2316. iframeDoc=curIframe.contentDocument || curIframe.contentWindow.document;
  2317. }catch(e){
  2318. debug("Stop as cors");
  2319. isPause=true;
  2320. callback(false, false);
  2321. return;
  2322. }
  2323. ruleParser.insertPage(iframeDoc, [], url, null, true);
  2324. callback(curIframe, true);
  2325. curIframe.style.height=iframeDoc.body.scrollHeight+"px";
  2326. curIframe.style.width=iframeDoc.body.scrollWidth+"px";
  2327. });
  2328. let inAction=false;
  2329. let forceRefresh=e=>{
  2330. if(inAction || !iframeDoc)return;
  2331. inAction=true;
  2332. setTimeout(()=>{
  2333. inAction=false;
  2334. curIframe.style.height=iframeDoc.body.scrollHeight+"px";
  2335. curIframe.style.width=iframeDoc.body.scrollWidth+"px";
  2336. if(!ruleParser.nextLinkHref){
  2337. ruleParser.getNextLink(iframeDoc);
  2338. if(ruleParser.nextLinkHref){
  2339. document.removeEventListener("scroll", forceRefresh);
  2340. }
  2341. }else{
  2342. document.removeEventListener("scroll", forceRefresh);
  2343. }
  2344. },500);
  2345. curIframe.style.height=iframeDoc.body.scrollHeight+"px";
  2346. curIframe.style.width=iframeDoc.body.scrollWidth+"px";
  2347. };
  2348. document.addEventListener("scroll", forceRefresh);
  2349. curIframe.src=url;
  2350. let insert=ruleParser.getInsert();
  2351. document.body.appendChild(curIframe);
  2352. return curIframe;
  2353. }
  2354.  
  2355. function loadPageOver(){
  2356. isLoading=false;
  2357. if(loadingDiv.parentNode){
  2358. loadingDiv.parentNode.removeChild(loadingDiv);
  2359. }
  2360. setTimeout(()=>{
  2361. let scrollH=Math.max(document.documentElement.scrollHeight, document.body.scrollHeight);
  2362. if(scrollH < (window.innerHeight || document.documentElement.clientHeight)){
  2363. nextPage();
  2364. }
  2365. },1);
  2366. }
  2367.  
  2368. function nextPage(){
  2369. if(isPause || isLoading)return;
  2370. let nextLink=ruleParser.nextLinkHref;
  2371. if(!nextLink)return;
  2372. let insert=ruleParser.getInsert();
  2373. if(insert){
  2374. let isJs=/^(javascript|#)/.test(nextLink.replace(location.href,""));
  2375. if(location.protocol=="https:" && /^http:/.test(nextLink)){
  2376. nextLink=nextLink.replace(/^http/,"https");
  2377. }
  2378. isLoading=true;
  2379. document.body.appendChild(loadingDiv);
  2380. let sleep=ruleParser.curSiteRule.sleep||0;
  2381. setTimeout(()=>{
  2382. if(ruleParser.curSiteRule.pageElementByJs){
  2383. var over=ele=>{
  2384. loadPageOver();
  2385. if(ele){
  2386. createPageBar(nextLink);
  2387. ruleParser.insertPage(null, ele, nextLink, null, true);
  2388. if(autoLoadNum>=0){
  2389. if(autoLoadNum!=0 && --autoLoadNum==0){
  2390. autoLoadNum=-1;
  2391. }else{
  2392. nextPage();
  2393. }
  2394. }
  2395. }else{
  2396. debug("Stop as no page when get by js");
  2397. isPause=true;
  2398. }
  2399. };
  2400. try{
  2401. Function("over",'"use strict";' + ruleParser.curSiteRule.pageElementByJs)(over);
  2402. }catch(e){
  2403. debug(e);
  2404. }
  2405. }else if(ruleParser.curSiteRule.action==1 && !isJs){
  2406. requestFromIframe(nextLink, (doc, eles)=>{
  2407. loadPageOver();
  2408. if(eles){
  2409. createPageBar(nextLink);
  2410. ruleParser.insertPage(doc, eles, nextLink, null, true);
  2411. if(autoLoadNum>=0){
  2412. if(autoLoadNum!=0 && --autoLoadNum==0){
  2413. autoLoadNum=-1;
  2414. }else{
  2415. nextPage();
  2416. }
  2417. }
  2418. }
  2419. });
  2420. }else if((forceState==2||ruleParser.curSiteRule.action==2) && !isJs){
  2421. forceIframe(nextLink, (iframe, eles)=>{
  2422. loadPageOver();
  2423. let pageBar=createPageBar(nextLink);
  2424. iframe.parentNode.insertBefore(pageBar, iframe);
  2425. if(autoLoadNum>=0){
  2426. if(autoLoadNum!=0 && --autoLoadNum==0){
  2427. autoLoadNum=-1;
  2428. }else{
  2429. nextPage();
  2430. }
  2431. }
  2432. });
  2433. }else{
  2434. if(!isJs){
  2435. requestDoc(nextLink, (eles)=>{
  2436. loadPageOver();
  2437. if(eles){
  2438. createPageBar(nextLink);
  2439. if(autoLoadNum>=0){
  2440. if(autoLoadNum!=0 && --autoLoadNum==0){
  2441. autoLoadNum=-1;
  2442. }else{
  2443. nextPage();
  2444. }
  2445. }
  2446. }
  2447. });
  2448. }else{
  2449. emuPage((doc, eles)=>{
  2450. loadPageOver();
  2451. if(eles){
  2452. createPageBar(nextLink);
  2453. ruleParser.insertPage(doc, eles, "", null, true);
  2454. if(autoLoadNum>=0){
  2455. if(autoLoadNum!=0 && --autoLoadNum==0){
  2456. autoLoadNum=-1;
  2457. }else{
  2458. nextPage();
  2459. }
  2460. }
  2461. }
  2462. });
  2463. }
  2464. }
  2465. },sleep);
  2466. }
  2467. }
  2468.  
  2469. function init(){
  2470. initRules(()=>{
  2471. initPage();
  2472. });
  2473. }
  2474. setTimeout(()=>{
  2475. init();
  2476. },300);
  2477. })();