東方永頁機

自動加載並拼接下一分頁內容(適用於論壇、漫畫站、小說站、資訊站、博客等),無需規則支持所有網頁

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