东方永页机

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

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

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