东方永页机

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

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

  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.3
  14. // @description Most compatible Auto pager script ever! Simply auto loading paginated web pages.
  15. // @description:zh-CN 自动加载并拼接下一分页内容(适用于论坛、漫画站、小说站、资讯站、博客等),无需规则支持所有网页
  16. // @description:zh-TW 自動加載並拼接下一分頁內容(適用於論壇、漫畫站、小說站、資訊站、博客等),無需規則支持所有網頁
  17. // @description:ja Webページを自動で読み込み継ぎ足し表示を行うブラウザ拡張です
  18. // @description:ru Просто автоматически загрузите следующую страницу
  19. // @description:de Laden Sie einfach automatisch die nächste Seite
  20. // @description:es Carga automática de páginas web paginadas
  21. // @description:fr Chargement automatique des pages Web paginées
  22. // @description:it Caricamento automatico di pagine Web impaginate
  23. // @description:ko 다음 페이지를 자동으로 로드하세요
  24. // @author hoothin
  25. // @include http://*
  26. // @include https://*
  27. // @license MIT
  28. // @icon data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAdVBMVEUAAAD3VU33VU32VEz8U073VU32VU33VU32VUz0Uk/3VE32VU32VUz2VU32VU32VU32VU33VU33U0z2VU34Wkv3VE32VUz/mpj/nJj2VUz2VU32VE33VEz2VU32VU32VUz3VE32VEz3VE3/mZf2Vkz2VU3/mpilFFolAAAAJXRSTlMA3Lp/GvTBT5YQLuawZ/DOyZwlPQeKc21N04+FX1bqpm9DNoB4T68ePwAAAitJREFUWMPt1tuasiAUBuCFCG5Rs3QybTPV1/1f4v/3PDkyIojn8x5qBrI+ltAfh32/yysmBKvyXb+njb6bDL9kzTd5SzjDAsYT8nFoGSxYe6BVqoNDp2jFDit25BRgVUAODB4YWcETWVTwVNGiGN5iWtBgg4YMCpsoI38dNunmmWyxUTvbPwwbsYR0fIzZLQ0pTG8eieRmBLMmpdH9uimQEf6TNRnXXKLZHixpJtywLzOgMHtFCqdM64DahHRnOE1dsrekm9wr2WtLcAlpdHwcp1pAJySXYnERclzp4+v19jXdmcTvQUJtz+ZaI4i05/V/UGYrCxbaAsOYoNfIKEQxpqQuzCgJJJ/3f42O8ywEZuMVWi/8hODxGj3GW2b0udkbGULLDOjimAG0S3fLGlBnXQM9irG1CiQdVQi0dqQsOSDlyEEz7Vy9OxxfR71VCXsSB23jMrKJYZXSjw57sqgLn5Z0wolsOCz0RyJkyeYjgz7pwwVq20eboZwtVUl2EnN5gJ50dQZFdryATvABRTr/tJXkUMdaAK5pwtCapwtFLskguwuyMh/Sd9WChQ4sIvIUYSk3PYqQvCQlOC04IfN7PkdjOyRKWhdKXMmiAFt9i3sJ5jxoRuR0vqAghxxwHuqfQE5OHGDKOrwEnqs1DgAZ2e4Eev1d45TN7JfhrQLKgfwMFYAsvp33dXII073aVQLI2gN5S58lfmGnKKFtah7nkgnBZB7zlP7Y/QNiTM6sYNzawwAAAABJRU5ErkJggg==
  29. // @grant GM_xmlhttpRequest
  30. // @grant GM_registerMenuCommand
  31. // @grant GM_notification
  32. // @grant GM_getValue
  33. // @grant GM_setValue
  34. // @grant GM_addStyle
  35. // @grant GM_openInTab
  36. // @grant GM_deleteValue
  37. // @grant GM.xmlHttpRequest
  38. // @grant GM.registerMenuCommand
  39. // @grant GM.notification
  40. // @grant GM.getValue
  41. // @grant GM.setValue
  42. // @grant GM.addStyle
  43. // @grant GM.openInTab
  44. // @grant GM.deleteValue
  45. // @supportURL https://github.com/hoothin/UserScripts/issues
  46. // @connect wedata.net
  47. // @connect githubusercontent.com
  48. // @run-at document-idle
  49. // @exclude http://www.toodledo.com/tasks/*
  50. // @exclude http*://maps.google.com*/*
  51. // @exclude *://www.google.*/_/chrome/newtab*
  52. // @exclude *://mega.*/*
  53. // @exclude *://*.mega.*/*
  54. // @exclude *://*.youku.com/v_*
  55. // @exclude *://*pan.baidu.com
  56. // @exclude *://*.iqiyi.com/v_*
  57. // @exclude *://*.iqiyi.com/w_*
  58. // @exclude *://*.iqiyi.com/a_*
  59. // @exclude *://*.le.com/ptv/vplay/*
  60. // @exclude *://v.qq.com/x/cover/*
  61. // @exclude *://v.qq.com/x/page/*
  62. // @exclude *://v.qq.com/tv/*
  63. // @exclude *://*.tudou.com/listplay/*
  64. // @exclude *://*.tudou.com/albumplay/*
  65. // @exclude *://*.tudou.com/programs/view/*
  66. // @exclude *://*.mgtv.com/b/*
  67. // @exclude *://film.sohu.com/album/*
  68. // @exclude *://tv.sohu.com/v/*
  69. // @exclude *://*.bilibili.com/video/*
  70. // @exclude *://*.bilibili.com/bangumi/play/*
  71. // @exclude *://*.baofeng.com/play/*
  72. // @exclude *://vip.pptv.com/show/*
  73. // @exclude *://v.pptv.com/show/*
  74. // @exclude *://www.le.com/ptv/vplay/*
  75. // @exclude *://www.wasu.cn/Play/show/*
  76. // @exclude *://m.v.qq.com/*
  77. // @exclude *://m.iqiyi.com/*
  78. // @exclude *://m.youku.com/alipay_video/*
  79. // @exclude *://m.mgtv.com/b/*
  80. // @exclude *://m.tv.sohu.com/v/*
  81. // @exclude *://m.film.sohu.com/album/*
  82. // @exclude *://m.le.com/ptv/vplay/*
  83. // @exclude *://m.pptv.com/show/*
  84. // @exclude *://m.acfun.cn/v/*
  85. // @exclude *://m.bilibili.com/video/*
  86. // @exclude *://m.bilibili.com/anime/*
  87. // @exclude *://m.bilibili.com/bangumi/play/*
  88. // @exclude *://m.wasu.cn/Play/show/*
  89. // @exclude *://www.youtube.com
  90. // @exclude *://www.youtube.com/
  91. // @exclude *://www.youtube.com/watch*
  92. // @exclude *://baike.baidu.com/*
  93. // @exclude *://*.instagram.com/*
  94. // @exclude *://order.jd.com/*
  95. // @exclude *://pagetual.hoothin.com/*
  96. // @exclude *://hoothin.github.io/PagetualGuide/*
  97. // @connect *
  98. // ==/UserScript==
  99.  
  100. (function() {
  101. 'use strict';
  102.  
  103. if (window.name === 'pagetual-iframe' || (window.frameElement && window.frameElement.name === 'pagetual-iframe')) {
  104. var domloaded = function (){
  105. window.scroll(window.scrollX, 999999);
  106. //window.parent.postMessage('pagetual-iframe:DOMLoaded', '*');
  107. };
  108. if(window.opera){
  109. document.addEventListener('DOMContentLoaded', domloaded, false);
  110. } else {
  111. domloaded();
  112. }
  113. return;
  114. }
  115.  
  116. if(window.top != window.self){
  117. try{
  118. if (top.location.hostname != window.location.hostname || window.top != window.parent) {
  119. return;
  120. }
  121. }catch(e){
  122. return;
  123. }
  124. }
  125.  
  126. const lang = navigator.appName=="Netscape"?navigator.language:navigator.userLanguage;
  127. var i18n=(name, param)=>{
  128. let config={};
  129. switch (lang){
  130. case "zh-CN":
  131. case "zh-SG":
  132. config={
  133. enableDebug:"调试模式,输出信息至控制台",
  134. disable:"暂时禁用",
  135. disableSite:"在此站禁用",
  136. enable:"启用翻页",
  137. toTop:"回到顶部",
  138. toBottom:"前往页尾",
  139. current:"当前页",
  140. forceIframe:"强制拼接",
  141. cancelForceIframe:"取消强制拼接",
  142. configure:"打开配置页",
  143. firstUpdate:"点击此处初始化规则",
  144. update:"更新规则",
  145. click2update:"点击立即更新规则",
  146. loadNow:"立即翻页",
  147. loadConfirm:"要翻几页?(0为不间断)",
  148. noNext:"没有找到下一页,请新建规则",
  149. passSec:"更新于 #t# 秒前",
  150. passMin:"更新于 #t# 分钟前",
  151. passHour:"更新于 #t# 小时前",
  152. passDay:"更新于 #t# 天前",
  153. cantDel:"无法删除内置规则",
  154. confirmDel:"是否确认要删除此规则?",
  155. updateSucc:"更新成功",
  156. beginUpdate:"正在更新,请稍候",
  157. customUrls:"导入规则url,一行一条,AutoPagerize 格式规则需要以\"0|\"开头",
  158. customRules:"输入【东方永页机】格式的自定义规则",
  159. save:"保存设置",
  160. loadingText:"少女祈祷中...",
  161. opacity:"分页隔条不透明值",
  162. hideBar:"空白处双击隐藏分页隔条",
  163. dbClick2Stop:"空白处双击暂停翻页",
  164. sortTitle:"排序在下次更新规则后生效",
  165. autoRun:"自动启用,否则为白名单模式",
  166. inputPageNum:"输入页码跳转",
  167. enableHistory:"翻页后写入历史记录",
  168. initRun:"打开页面后立即尝试翻页,否则滚动至页尾再翻页",
  169. preload:"翻页前预读下一页,加速浏览"
  170. };
  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(aTag.href && /next$/i.test(aTag.href))continue;
  870. if(!next1){
  871. if(/^[下后後][一1]?[页頁张張]|^next( page)?\s*›?$|次のページ/i.test(aTag.innerText.trim())){
  872. if(aTag.innerText.length>15)continue;
  873. if(!aTag.href || /^javascript:/.test(aTag.href)){
  874. if(!nextJs1)nextJs1=aTag;
  875. }else{
  876. next1=aTag;
  877. }
  878. }
  879. }
  880. if(!next2){
  881. if(/^[下后後][一1]?[章话話]/i.test(aTag.innerText.trim())){
  882. if(!aTag.href || /^javascript:/.test(aTag.href)){
  883. if(!nextJs2)nextJs2=aTag;
  884. }else{
  885. next2=aTag;
  886. }
  887. }
  888. }
  889. if(!next3){
  890. if(aTag.innerText=="&gt;" || aTag.innerText=="▶" || aTag.innerText==">" || aTag.innerText=="›" || /nextpage/i.test(aTag.className)){
  891. if(!aTag.href || /^javascript:/.test(aTag.href)){
  892. if(!nextJs3)nextJs3=aTag;
  893. }else{
  894. next3=aTag;
  895. }
  896. }
  897. }
  898. if(!aTag.href || /^javascript:/.test(aTag.href))continue;
  899. if(!next4){
  900. if(pageNum<999 && aTag.href.replace("?&","?").replace("#!","").replace("index.php?","?").replace(preStr,"").replace(afterStr,"")==pageNum+1){
  901. next4=aTag;
  902. }else if(this.curUrl!=aTag.href && aTag.href.replace("?&","?").replace("index.php?","?").indexOf(url)!=-1 && /^[\/\?&]?[_-]?(p|page)?=?\/?2(\/|\?|&|$)/i.test(aTag.href.replace(url,"").replace(/\.s?html?$/i,""))){
  903. let curHref=aTag.getAttribute("href");
  904. let pageOne=curHref.replace(/\/2(\/|\?|&|$)/,"/1$1");
  905. if(pageOne==curHref)pageOne=null;
  906. else pageOne=curPage.querySelector(`a[href='${pageOne}']`);
  907. if(!pageOne)next4=aTag;
  908. }
  909. }
  910. }
  911. next=next1||next3||next4||next2||nextJs1||nextJs3||nextJs2;
  912. }
  913. if(!next)next=jsNext;
  914. if(next && next.classList.contains("results-more"))next=null;
  915. return {next:next,canSave:canSave};
  916. }
  917.  
  918. canonicalUri(src, base_path) {
  919. if(src.charAt(0)=="#")return location.href+src;
  920. var root_page = /^[^?#]*\//.exec(location.href)[0],
  921. root_domain = /^\w+\:\/\/\/?[^\/]+/.exec(root_page)[0],
  922. absolute_regex = /^\w+\:\/\//;
  923. src=src.replace(/\.\//,"");
  924. if (/^\/\/\/?/.test(src)){
  925. src = location.protocol + src;
  926. }
  927. else if (!absolute_regex.test(src) && src.charAt(0) != "/"){
  928. src = (base_path || "") + src;
  929. }
  930. return (absolute_regex.test(src) ? src : ((src.charAt(0) == "/" ? root_domain : root_page) + src));
  931. }
  932.  
  933. getLinkByPage(url, pageNum) {
  934. if(!url)return;
  935. if(this.curSiteRule.pageNum){
  936. let result=this.curSiteRule.pageNum;
  937. let strMatch=result.match(/\{.*?}/);
  938. if(!strMatch)return null;
  939. let urlReg=new RegExp("("+result.replace(strMatch[0], ")\\d+(")+")");
  940. let code=strMatch[0].replace(/^{/,"").replace(/}$/,"").replace(/\$p/g,pageNum);
  941. if(code==pageNum){
  942. result=url.replace(urlReg,"$1"+code+"$2");
  943. }else{
  944. try{
  945. code=Function('"use strict";return ' + code)();
  946. result=url.replace(urlReg,"$1"+code+"$2");
  947. }catch(e){
  948. debug(e);
  949. }
  950. }
  951. return result==url?url.replace(/([&\/\?](p=|page[=\/]))\d+/i, "$1"+pageNum):result;
  952. }else{
  953. return url.replace(/([&\/\?](p=|page[=\/]))\d+/i, "$1"+pageNum);
  954. }
  955. }
  956.  
  957. getNextLink(doc) {
  958. let nextLink=null,page;
  959. if(this.curSiteRule.pageElementByJs){
  960. this.nextLinkHref="#";
  961. return true;
  962. }else if(this.curSiteRule.nextLinkByJs){
  963. try{
  964. let targetUrl=Function("doc",'"use strict";' + this.curSiteRule.nextLinkByJs)(doc);
  965. if(targetUrl)nextLink={href:targetUrl};
  966. }catch(e){
  967. debug(e);
  968. }
  969. }else if(this.curSiteRule.nextLinkByUrl){
  970. let targetUrl=this.curUrl.replace(new RegExp(this.curSiteRule.nextLinkByUrl[0]), this.curSiteRule.nextLinkByUrl[1]);
  971. if(targetUrl != this.curUrl){
  972. let reps=targetUrl.match(/{.*?}/g);
  973. if(reps){
  974. reps.forEach(rep=>{
  975. let code=rep.replace("{","").replace("}","");
  976. let result=code.match(/^(\d+)\+1$/);
  977. if(result){
  978. result=parseInt(result[1])+1;
  979. }else{
  980. try{
  981. result=Function('"use strict";return ' + code)();
  982. }catch(e){
  983. debug(e);
  984. }
  985. }
  986. targetUrl=targetUrl.replace(rep, result);
  987. });
  988. }
  989. }
  990. nextLink={href:targetUrl};
  991. }else if(this.curSiteRule.nextLink){
  992. if(this.curSiteRule.nextLink!="0"){
  993. nextLink=this.curSiteRule.type==0?getElementByXpath(this.curSiteRule.nextLink,doc,doc):doc.querySelector(this.curSiteRule.nextLink);
  994. }
  995. }else{
  996. page=this.getPage(doc);
  997. nextLink=page.next;
  998. if(nextLink){
  999. if(nextLink.tagName=="INPUT" && nextLink.parentNode.tagName=="FORM"){
  1000. let params=[];
  1001. let form=nextLink.parentNode;
  1002. [].forEach.call(form.querySelectorAll("input"), input=>{
  1003. params.push(input.name+'='+input.value);
  1004. });
  1005. nextLink.href=form.action+'?'+params.join('&');
  1006. }
  1007. if(nextLink.classList.contains("noClick")){
  1008. this.nextLinkHref=false;
  1009. return null;
  1010. }else if(doc==document){
  1011. if((!nextLink.href || /^javascript:/.test(nextLink.href)) && !isVisible(nextLink, _unsafeWindow)){
  1012. this.nextLinkHref=false;
  1013. return null;
  1014. }else{
  1015. let nextLinkCs=_unsafeWindow.getComputedStyle(nextLink);
  1016. if(nextLinkCs.cursor=="not-allowed"){
  1017. this.nextLinkHref=false;
  1018. return null;
  1019. }
  1020. }
  1021. }
  1022. }
  1023. }
  1024. if(nextLink){
  1025. if(nextLink.href===""){
  1026. this.nextLinkHref=false;
  1027. }else if(nextLink.href && (nextLink.href==this.curUrl || nextLink.href==this.oldUrl)){
  1028. this.nextLinkHref=false;
  1029. }else if(/^javascript:/.test(nextLink.href) && (this.curSiteRule.action==0 || this.curSiteRule.action==1)){
  1030. this.nextLinkHref=false;
  1031. }else{
  1032. this.nextLinkHref=(nextLink.href && !/^javascript:/.test(nextLink.href))?this.canonicalUri(nextLink.href):"#";
  1033. if(doc==document)debug(nextLink);
  1034. }
  1035. }else{
  1036. this.nextLinkHref=false;
  1037. }
  1038. this.preload();
  1039. return nextLink;
  1040. }
  1041.  
  1042. preload(){
  1043. if(!rulesData.preload)return;
  1044. if(!this.nextLinkHref || this.nextLinkHref=="#")return;
  1045. let self=this;
  1046. if(this.curSiteRule && this.curSiteRule.action==1){
  1047. if(!this.preloadIframe){
  1048. this.preloadIframe = document.createElement('iframe');
  1049. let iframe = this.preloadIframe;
  1050. iframe.name = 'pagetual-iframe';
  1051. iframe.width = '100%';
  1052. iframe.height = '0';
  1053. iframe.frameBorder = '0';
  1054. if(ruleParser.curSiteRule.sandbox!=false){
  1055. iframe.sandbox="allow-same-origin allow-scripts allow-popups allow-forms";
  1056. }
  1057. iframe.style.cssText = 'margin:0!important;padding:0!important;visibility:hidden!important;';
  1058. iframe.addEventListener('load', function (e) {
  1059. try{
  1060. let doc=iframe.contentDocument || iframe.contentWindow.document;
  1061. var body = doc.body;
  1062. if (body && body.firstChild) {
  1063. self.lazyImgAction(body.children);
  1064. }
  1065. }catch(e){
  1066. return;
  1067. }
  1068. }, false);
  1069. document.body.appendChild(iframe);
  1070. }
  1071. this.preloadIframe.src = this.nextLinkHref;
  1072. }else{
  1073. _GM_xmlhttpRequest({
  1074. url: this.nextLinkHref,
  1075. method: 'GET',
  1076. overrideMimeType: 'text/html;charset='+document.charset,
  1077. headers: {
  1078. 'Referer': location.href
  1079. },
  1080. timeout: 5000,
  1081. onload: function(res) {
  1082. var doc=null;
  1083. try {
  1084. doc=document.implementation.createHTMLDocument('');
  1085. doc.documentElement.innerHTML=res.response;
  1086. var body = doc.body;
  1087. if (body && body.firstChild) {
  1088. self.lazyImgAction(body.children);
  1089. }
  1090. if(!self.preloadDiv){
  1091. self.preloadDiv = document.createElement('div');
  1092. self.preloadDiv.id = "pagetual-preload";
  1093. self.preloadDiv.style.cssText = 'display:none!important;';
  1094. document.body.appendChild(self.preloadDiv);
  1095. self.checkedImgs={};
  1096. }
  1097. [].forEach.call(doc.images, i=>{
  1098. let iSrc=i.src;
  1099. if(iSrc && !self.checkedImgs[iSrc]){
  1100. self.checkedImgs[iSrc] = true;
  1101. let img = document.createElement('img');
  1102. img.src = iSrc;
  1103. self.preloadDiv.appendChild(img);
  1104. }
  1105. });
  1106. }
  1107. catch (e) {
  1108. return;
  1109. }
  1110. }
  1111. });
  1112. }
  1113. }
  1114.  
  1115. getInsert(refresh) {
  1116. if(refresh){
  1117. this.insert=null;
  1118. }
  1119. if(this.insert && !refresh){
  1120. let parent=this.insert;
  1121. while(parent && parent.nodeName!="BODY"){
  1122. parent=parent.parentNode;
  1123. }
  1124. if(parent && parent.nodeName=="BODY"){
  1125. return this.insert;
  1126. }
  1127. }
  1128. if(this.curSiteRule.insert){
  1129. this.insert=this.curSiteRule.type==0?getElementByXpath(this.curSiteRule.insert,document):document.querySelector(this.curSiteRule.insert);
  1130. }else{
  1131. let pageElement=this.getPageElement(document, _unsafeWindow);
  1132. if(pageElement && pageElement.length>0){
  1133. var pELast = pageElement[pageElement.length - 1];
  1134. this.insert = pELast.nextSibling ? pELast.nextSibling : pELast.parentNode.appendChild(document.createTextNode(' '));
  1135. }
  1136. }
  1137. return this.insert;
  1138. }
  1139.  
  1140. pageInit(doc,eles){
  1141. let code=this.curSiteRule.pageInit;
  1142. if(code){
  1143. try{
  1144. Function("doc","eles",'"use strict";' + code)(doc,eles);
  1145. }catch(e){
  1146. debug(e);
  1147. }
  1148. }
  1149. }
  1150.  
  1151. pageAction(doc,eles){
  1152. let code=this.curSiteRule.pageAction;
  1153. if(code){
  1154. try{
  1155. Function("doc","eles",'"use strict";' + code)(doc,eles);
  1156. }catch(e){
  1157. debug(e);
  1158. }
  1159. }
  1160. this.lazyImgAction(eles);
  1161. }
  1162.  
  1163. lazyImgAction(eles){
  1164. let setLazyImg=img=>{
  1165. let realSrc;
  1166. if(img.getAttribute("_src") && !img.src){
  1167. realSrc=img.getAttribute("_src");
  1168. }else if(img.dataset && img.dataset.original){
  1169. realSrc=img.dataset.original;
  1170. }else if(img.dataset && img.dataset.src){
  1171. realSrc=img.dataset.src;
  1172. }else if(img._lazyrias && img._lazyrias.srcset){
  1173. realSrc=img._lazyrias.srcset[img._lazyrias.srcset.length-1];
  1174. }else if(img.dataset && img.dataset.origFile){
  1175. realSrc=img.dataset.origFile;
  1176. }else if(img.srcset){
  1177. var srcs=img.srcset.split(","),largeSize=0;
  1178. srcs.forEach(srci=>{
  1179. let srcInfo=srci.trim().split(" "),curSize=parseInt(srcInfo[1]);
  1180. if(srcInfo[1] && curSize>largeSize){
  1181. largeSize=curSize;
  1182. realSrc=srcInfo[0];
  1183. }
  1184. });
  1185. }
  1186. if(realSrc){
  1187. img.src=realSrc;
  1188. img.style.display="block";
  1189. }
  1190. };
  1191. [].forEach.call(eles, ele=>{
  1192. if(ele.tagName=="IMG"){
  1193. setLazyImg(ele);
  1194. }else{
  1195. [].forEach.call(ele.querySelectorAll("img"), img=>{
  1196. setLazyImg(img);
  1197. });
  1198. }
  1199. if(ele.tagName=="A" && ele.classList.contains("lazyload")){
  1200. if(ele.dataset.original){
  1201. ele.style.backgroundImage='url("'+ele.dataset.original+'")';
  1202. }
  1203. }else{
  1204. [].forEach.call(ele.querySelectorAll("a.lazyload"), a=>{
  1205. if(a.dataset.original){
  1206. a.style.backgroundImage='url("'+a.dataset.original+'")';
  1207. }
  1208. });
  1209. }
  1210. });
  1211. let lazyImgSrc=this.curSiteRule.lazyImgSrc;
  1212. if(lazyImgSrc){
  1213. [].forEach.call(eles, ele=>{
  1214. [].forEach.call(ele.querySelectorAll("img"), img=>{
  1215. if(img.getAttribute(lazyImgSrc)){
  1216. img.src=img.getAttribute(lazyImgSrc);
  1217. }
  1218. });
  1219. });
  1220. }
  1221. }
  1222.  
  1223. initPage(callback){
  1224. let self=this;
  1225. curPage=1;
  1226. //if(this.curSiteRule.url && !this.curSiteRule.singleUrl)return;
  1227. this.curSiteRule={};
  1228. this.pageDoc=document;
  1229. this.nextLinkHref=null;
  1230. this.curUrl=location.href;
  1231. this.getRule(()=>{
  1232. if(self.curSiteRule.enable==0){
  1233. debug("Stop as rule disable");
  1234. isPause=true;
  1235. return;
  1236. }
  1237. if(self.curSiteRule && !self.curSiteRule.singleUrl){
  1238. self.hpRules=self.hpRules.filter(item=>{return item&&item.url!=self.curSiteRule.url});
  1239. self.hpRules.unshift(self.curSiteRule);
  1240. if(self.hpRules.length>30){
  1241. self.hpRules.pop();
  1242. }
  1243. storage.setItem("hpRules", self.hpRules);
  1244. }
  1245. let css=self.curSiteRule.css;
  1246. if(css){
  1247. _GM_addStyle(css);
  1248. }
  1249. let code=self.curSiteRule.init;
  1250. if(code){
  1251. try{
  1252. Function('doc','win','"use strict";' + code)(null,null);
  1253. }catch(e){
  1254. debug(e);
  1255. }
  1256. }
  1257. self.getNextLink(document);
  1258. callback();
  1259. });
  1260. }
  1261.  
  1262. insertPage(doc, eles, url, callback, tried){
  1263. this.oldUrl=this.curUrl;
  1264. let oldTitle=this.pageDoc.title;
  1265. this.pageDoc=doc;
  1266. this.curUrl=url;
  1267. let nextLink=this.getNextLink(doc);
  1268. if(curPage==1 && !tried && !nextLink && this.curSiteRule.singleUrl && this.curSiteRule.pageElement && this.curSiteRule.pageElement!=allOfBody){
  1269. this.curSiteRule.action=1;
  1270. this.curUrl=location.href;
  1271. return false;
  1272. }
  1273. if(callback)callback(eles);
  1274. this.getInsert();
  1275. var self=this,newEles=[];
  1276. if(!eles || eles.length==0 || !self.insert || !self.insert.parentNode){
  1277. }else{
  1278. this.pageInit(doc, eles);
  1279. [].forEach.call(eles, ele=>{
  1280. let newEle=ele.cloneNode(true);
  1281. let oldCanvass=ele.querySelectorAll("canvas");
  1282. let newCanvass=newEle.querySelectorAll("canvas");
  1283. for(let i=0;i<oldCanvass.length;i++){
  1284. let oldCanvas=oldCanvass[i];
  1285. let newCanvas=newCanvass[i];
  1286. newCanvas.getContext('2d').drawImage(oldCanvas, 0, 0);
  1287. }
  1288. if(self.curSiteRule.insertPos==2){
  1289. self.insert.appendChild(newEle);
  1290. }else{
  1291. self.insert.parentNode.insertBefore(newEle, self.insert);
  1292. }
  1293. newEles.push(newEle);
  1294. });
  1295. }
  1296. this.pageAction(doc, newEles);
  1297. if(this.oldUrl!=location.href){
  1298. let isJs=/^(javascript|#)/.test(this.oldUrl.replace(location.href,""));
  1299. if(rulesData.enableHistory && !isJs){
  1300. _unsafeWindow.history.replaceState(undefined, oldTitle, this.oldUrl);
  1301. document.title=oldTitle;
  1302. }
  1303. }
  1304. return true;
  1305. }
  1306. }
  1307. var ruleParser = new RuleParser();
  1308.  
  1309. function initConfig(){
  1310. _GM_registerMenuCommand(i18n(forceState==1?"enable":"disableSite"), ()=>{
  1311. storage.setItem("forceState_"+location.host, (forceState==1?0:1));
  1312. location.reload();
  1313. });
  1314. _GM_registerMenuCommand(i18n("update"), ()=>{
  1315. updateRules(()=>{
  1316. alert(i18n("updateSucc"));
  1317. location.reload();
  1318. },(rule,err)=>{
  1319. alert("Update "+rule.url+" rules fail!");
  1320. });
  1321. alert(i18n("beginUpdate"));
  1322. });
  1323.  
  1324. var configCon,insertPos;
  1325. if(location.href==configPage){
  1326. _GM_addStyle(`
  1327. p>span:nth-child(1),p>span:nth-child(2),p>span:nth-child(3){
  1328. cursor: pointer;
  1329. user-select: none;
  1330. }
  1331. p>span:nth-child(1):hover,p>span:nth-child(2):hover,p>span:nth-child(3):hover{
  1332. color:red;
  1333. }
  1334. .updateDate{
  1335. cursor: pointer;
  1336. user-select: none;
  1337. }
  1338. .updateDate:hover{
  1339. color:red;
  1340. }
  1341. `);
  1342. configCon=document.querySelector(".markdown-body");
  1343. insertPos=configCon.querySelector("hr");
  1344. }else if(location.href==configPage){//2nd todo
  1345. }else return false;
  1346. class Rulebar {
  1347. init(ruleUrl){
  1348. this.ruleUrl=ruleUrl;
  1349. this.item=document.createElement("p");
  1350. this.item.title=ruleUrl.type==0?"AutoPagerize Rules":"Pagetual Rules";
  1351. this.item.dataset.id=this.ruleUrl.id;
  1352. let url=document.createElement("span");
  1353. url.innerHTML=ruleUrl.url;
  1354. let up=document.createElement("span");
  1355. up.innerHTML="↑ ";
  1356. up.title=i18n("sortTitle");
  1357. let down=document.createElement("span");
  1358. down.innerHTML="↓ ";
  1359. down.title=i18n("sortTitle");
  1360. let del=document.createElement("span");
  1361. del.innerHTML="× ";
  1362. up.onclick=e=>{
  1363. this.moveUp();
  1364. };
  1365. down.onclick=e=>{
  1366. this.moveDown();
  1367. };
  1368. del.onclick=e=>{
  1369. this.del();
  1370. };
  1371. this.item.appendChild(up);
  1372. this.item.appendChild(down);
  1373. this.item.appendChild(del);
  1374. this.item.appendChild(url);
  1375. configCon.insertBefore(this.item, insertPos);
  1376. }
  1377. saveSort(){
  1378. let sort=[];
  1379. [].forEach.call(this.item.parentNode.querySelectorAll("p[data-id]"), i=>{
  1380. sort.push(i.dataset.id);
  1381. });
  1382. rulesData.sort=sort;
  1383. storage.setItem("rulesData", rulesData);
  1384. }
  1385. moveUp(){
  1386. let preE=this.item.previousElementSibling;
  1387. if(preE.tagName=="P" && preE.children.length>1){
  1388. this.item.parentNode.insertBefore(this.item,preE);
  1389. this.saveSort();
  1390. }
  1391. }
  1392. moveDown(){
  1393. let nextE=this.item.nextElementSibling;
  1394. if(nextE.tagName=="P" && nextE.children.length>1){
  1395. this.item.parentNode.insertBefore(nextE,this.item);
  1396. this.saveSort();
  1397. }
  1398. }
  1399. del(){
  1400. if(this.ruleUrl.id<2){
  1401. alert(i18n("cantDel"));
  1402. }else if(window.confirm(i18n("confirmDel"))){
  1403. for(let u=0;u<rulesData.urls.length;u++){
  1404. if(this.ruleUrl.id==rulesData.urls[u].id){
  1405. rulesData.urls.splice(u,1);
  1406. break;
  1407. }
  1408. }
  1409. for(let u=0;u<rulesData.sort.length;u++){
  1410. if(this.ruleUrl.id==rulesData.sort[u]){
  1411. rulesData.sort.splice(u,1);
  1412. break;
  1413. }
  1414. }
  1415. storage.setItem("rulesData", rulesData);
  1416. ruleParser.rules=ruleParser.rules.filter(item=>{return item.from!=this.ruleUrl.id});
  1417. storage.setItem("rules", ruleParser.rules);
  1418. this.item.parentNode.removeChild(this.item);
  1419. //location.reload();
  1420. }
  1421. }
  1422. }
  1423. let updateP=document.createElement("p"),i=0;
  1424. let now=new Date().getTime(),inUpdate=false;
  1425.  
  1426.  
  1427. let pastDate=(new Date(updateDate)).toString(),passStr;
  1428. let passTime=(now-updateDate)/1000;
  1429. if(isNaN(passTime)){
  1430. passStr=i18n("firstUpdate");
  1431. }else if(passTime<60){
  1432. passStr=i18n("passSec", parseInt(passTime))+" ← "+i18n("click2update");
  1433. }else if(passTime<60*60){
  1434. passStr=i18n("passMin", parseInt(passTime/60))+" ← "+i18n("click2update");
  1435. }else if(passTime<60*60*24){
  1436. passStr=i18n("passHour", parseInt(passTime/3600))+" ← "+i18n("click2update");
  1437. }else{
  1438. passStr=i18n("passDay", parseInt(passTime/86400))+" ← "+i18n("click2update");
  1439. }
  1440.  
  1441.  
  1442. updateP.className="updateDate";
  1443. updateP.innerHTML=passStr;
  1444. updateP.title=i18n("update")+" - "+pastDate;
  1445. updateP.onclick=e=>{
  1446. updateRules(()=>{
  1447. alert(i18n("updateSucc"));
  1448. updateP.innerHTML=i18n("passSec", 0);
  1449. updateP.title=i18n("update");
  1450. },(rule,err)=>{
  1451. alert("Update "+rule.url+" rules fail!");
  1452. });
  1453. alert(i18n("beginUpdate"));
  1454. };
  1455. configCon.insertBefore(updateP, insertPos);
  1456. if(ruleUrls){
  1457. ruleUrls.forEach(ruleUrl=>{
  1458. var rulebar=new Rulebar();
  1459. rulebar.init(ruleUrl);
  1460. });
  1461. }
  1462. let customUrlsTitle=document.createElement("h2");
  1463. customUrlsTitle.innerHTML=i18n("customUrls");
  1464. configCon.insertBefore(customUrlsTitle, insertPos);
  1465. let customUrlsInput=document.createElement("textarea");
  1466. customUrlsInput.style.width="100%";
  1467. customUrlsInput.placeholder="0|http://wedata.net/databases/AutoPagerize/items_all.json";
  1468. configCon.insertBefore(customUrlsInput, insertPos);
  1469.  
  1470. let opacityTitle=document.createElement("h2");
  1471. opacityTitle.innerHTML=i18n("opacity");
  1472. let opacityInput=document.createElement("input");
  1473. opacityInput.value=rulesData.opacity*100;
  1474. opacityInput.type="number";
  1475. opacityInput.style.width="50px";
  1476. opacityInput.style.margin="0 0 0 10px";
  1477. opacityTitle.appendChild(opacityInput);
  1478. configCon.insertBefore(opacityTitle, insertPos);
  1479.  
  1480. function createCheckbox(innerText, val){
  1481. let title=document.createElement("h2");
  1482. title.innerHTML=innerText;
  1483. let input=document.createElement("input");
  1484. input.type="checkbox";
  1485. input.style.width="50px";
  1486. input.style.height="20px";
  1487. input.checked=val;
  1488. title.appendChild(input);
  1489. configCon.insertBefore(title, insertPos);
  1490. return input;
  1491. }
  1492.  
  1493. let hideBarInput=createCheckbox(i18n("hideBar"), rulesData.hideBar);
  1494. let dbClick2StopInput=createCheckbox(i18n("dbClick2Stop"), rulesData.dbClick2Stop);
  1495. let enableWhiteListInput=createCheckbox(i18n("autoRun"), rulesData.enableWhiteList!=true);
  1496. let enableDebugInput=createCheckbox(i18n("enableDebug"), rulesData.enableDebug!=false);
  1497. let enableHistoryInput=createCheckbox(i18n("enableHistory"), rulesData.enableHistory===true);
  1498. let initRunInput=createCheckbox(i18n("initRun"), rulesData.initRun!=false);
  1499. let preloadInput=createCheckbox(i18n("preload"), rulesData.preload);
  1500.  
  1501. let customRulesTitle=document.createElement("h2");
  1502. customRulesTitle.innerHTML=i18n("customRules")
  1503. configCon.insertBefore(customRulesTitle, insertPos);
  1504. let customRulesInput=document.createElement("textarea");
  1505. customRulesInput.style.width="100%";
  1506. customRulesInput.style.height="500px";
  1507. 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]`;
  1508. customRulesInput.value=getFormatJSON(ruleParser.customRules);
  1509. configCon.insertBefore(customRulesInput, insertPos);
  1510. let saveBtn=document.createElement("button");
  1511. saveBtn.innerHTML=i18n("save");
  1512. saveBtn.style.width="100%";
  1513. configCon.insertBefore(saveBtn, insertPos);
  1514. saveBtn.onclick=e=>{
  1515. try{
  1516. storage.setItem("hpRules", []);
  1517. if(customRulesInput.value==""){
  1518. storage.setItem("customRules", "");
  1519. }else{
  1520. let customRules=JSON.parse(customRulesInput.value);
  1521. if(Array && Array.isArray && !Array.isArray(customRules)){
  1522. alert("Rules must be a Array!");
  1523. return;
  1524. }
  1525. debug(customRules);
  1526. storage.setItem("customRules", customRules);
  1527. }
  1528. }catch(e){
  1529. debug(e);
  1530. alert("JSON error, check again!");
  1531. return;
  1532. }
  1533. rulesData.opacity=opacityInput.value/100;
  1534. rulesData.hideBar=hideBarInput.checked;
  1535. rulesData.dbClick2Stop=dbClick2StopInput.checked;
  1536. rulesData.enableWhiteList=!enableWhiteListInput.checked;
  1537. rulesData.enableDebug=enableDebugInput.checked;
  1538. rulesData.enableHistory=enableHistoryInput.checked;
  1539. rulesData.initRun=initRunInput.checked;
  1540. rulesData.preload=preloadInput.checked;
  1541. storage.setItem("rulesData", rulesData);
  1542. let customUrls=customUrlsInput.value.trim();
  1543. if(customUrls){
  1544. customUrls=customUrls.split(/\n/);
  1545. for(let c=0;c<customUrls.length;c++){
  1546. let urlArr=customUrls[c].split("|"),url,type=1;
  1547. if(urlArr.length==1){
  1548. url=urlArr[0].trim();
  1549. if(!/^http/.test(url)){
  1550. alert("Wrong url, check again!");
  1551. return;
  1552. }
  1553. }else if(urlArr.length==2){
  1554. type=urlArr[0].trim();
  1555. url=urlArr[1].trim();
  1556. if(!/^http/.test(url)){
  1557. alert("Wrong url, check again!");
  1558. return;
  1559. }
  1560. }else{
  1561. break;
  1562. }
  1563. let maxId=0,hasUrl=false;
  1564. if(!rulesData.urls){
  1565. rulesData.urls=[];
  1566. maxId=1;
  1567. }else{
  1568. rulesData.urls.forEach(u=>{
  1569. if(maxId<u.id){
  1570. maxId=u.id;
  1571. }
  1572. if(u.url==url){
  1573. hasUrl=true;
  1574. }
  1575. });
  1576. if(hasUrl)break;
  1577. }
  1578. rulesData.urls.push({id:maxId+1,url:url,type:type});
  1579. rulesData.sort.push(maxId+1);
  1580. storage.setItem("rulesData", rulesData);
  1581. }
  1582. }
  1583. alert("The settings are saved");
  1584. location.reload();
  1585. };
  1586. return true;
  1587. }
  1588.  
  1589. var inUpdate=false;
  1590. function updateRules(success,fail){
  1591. if(inUpdate)return;
  1592. inUpdate=true;
  1593. let ruleIndex=ruleUrls.length-1;
  1594. storage.setItem("hpRules", []);
  1595. function addNextRule(){
  1596. if(ruleIndex<0){
  1597. let now=new Date().getTime();
  1598. storage.setItem("ruleLastUpdate", now);
  1599. storage.setItem("rules", ruleParser.rules);
  1600. inUpdate=false;
  1601. success();
  1602. }else{
  1603. let rule=ruleUrls[ruleIndex--];
  1604. ruleParser.addRuleByUrl(rule.url, rule.type, rule.id, (json,err)=>{
  1605. if(!json){
  1606. fail(rule,err);
  1607. }
  1608. addNextRule();
  1609. })
  1610. }
  1611. }
  1612. addNextRule();
  1613. }
  1614.  
  1615. function objIsArr(obj) {
  1616. return obj &&
  1617. typeof obj === 'object' &&
  1618. typeof obj.length === 'number' &&
  1619. !(obj.propertyIsEnumerable('length'));
  1620. }
  1621.  
  1622. function isVisible(el, win) {
  1623. if(!el.offsetParent)return false;
  1624. var loopable = true,
  1625. visible = el.tagName && win.getComputedStyle(el).display != 'none' && win.getComputedStyle(el).visibility != 'hidden';
  1626. while(loopable && visible) {
  1627. el = el.parentNode;
  1628.  
  1629. if(el && el.tagName && el.tagName!="BODY") {
  1630. visible = win.getComputedStyle(el).display != 'none' && win.getComputedStyle(el).visibility != 'hidden';
  1631. }else {
  1632. loopable = false;
  1633. }
  1634. }
  1635. return visible;
  1636. }
  1637.  
  1638. function getFormatJSON(obj){
  1639. if(!objIsArr(obj))return "";
  1640. let ret="[\n";
  1641. let len=obj.length,i=0,isLast;
  1642. obj.forEach(item=>{
  1643. ret+=" {\n";
  1644. let iLen=Object.keys(item).length,j=0;
  1645. for(let key in item){
  1646. isLast=(++j)==iLen;
  1647. let value=item[key];
  1648. if(objIsArr(value)){
  1649. let vstr="[",v=0,vIsLast=false;
  1650. value.forEach(vi=>{
  1651. vIsLast=(++v)==value.length;
  1652. vstr+="\""+vi.replace(/\\/g,"\\\\")+"\""+(vIsLast?"":",");
  1653. });
  1654. vstr+="]";
  1655. ret+=" \""+key+"\":"+vstr+""+(isLast?"":",")+"\n";
  1656. }else{
  1657. if(typeof value=="string"){
  1658. value=value.replace(/\\/g,"\\\\").replace(/"/g,"\\\"");
  1659. value="\""+value+"\"";
  1660. }
  1661. ret+=" \""+key+"\":"+value+""+(isLast?"":",")+"\n";
  1662. }
  1663. }
  1664. isLast=(++i)==len;
  1665. ret+=" }"+(isLast?"":",")+"\n";
  1666. });
  1667. ret+="]";
  1668. return ret;
  1669. }
  1670.  
  1671. function initRules(callback) {
  1672. /*0 wedata格式,1 pagetual格式*/
  1673. ruleUrls=[
  1674. {
  1675. id:0,
  1676. url:'https://raw.githubusercontent.com/hoothin/UserScripts/master/Pagetual/pagetualRules.json',
  1677. type:1
  1678. },
  1679. {
  1680. id:1,
  1681. url:'http://wedata.net/databases/AutoPagerize/items_all.json',
  1682. type:0,
  1683. }
  1684. ];var i=0,j=0;
  1685.  
  1686. ruleParser.initSavedRules(()=>{
  1687. storage.getItem("rulesData", data=>{
  1688. if(data){
  1689. rulesData=data;
  1690. if(data.urls)ruleUrls=ruleUrls.concat(data.urls);
  1691. if(data.sort){
  1692. let urls=[];
  1693. data.sort.forEach(id=>{
  1694. for(let s=0;s<ruleUrls.length;s++){
  1695. if(id==ruleUrls[s].id){
  1696. urls.push(ruleUrls[s]);
  1697. break;
  1698. }
  1699. }
  1700. });
  1701. ruleUrls=urls;
  1702. }
  1703. }
  1704. if(typeof(rulesData.opacity)=="undefined"){
  1705. rulesData.opacity=0.3;
  1706. }
  1707. if(typeof(rulesData.hideBar)=="undefined"){
  1708. rulesData.hideBar=false;
  1709. }
  1710. if(typeof(rulesData.dbClick2Stop)=="undefined"){
  1711. rulesData.dbClick2Stop=true;
  1712. }
  1713. if(typeof(rulesData.enableWhiteList)=="undefined"){
  1714. rulesData.enableWhiteList=false;
  1715. }
  1716. if(typeof(rulesData.enableHistory)=="undefined"){
  1717. rulesData.enableHistory=false;
  1718. }
  1719. if(typeof(rulesData.enableDebug)=="undefined"){
  1720. rulesData.enableDebug=true;
  1721. }
  1722. if(typeof(rulesData.initRun)=="undefined"){
  1723. rulesData.initRun=true;
  1724. }
  1725. if(typeof(rulesData.preload)=="undefined"){
  1726. rulesData.preload=false;
  1727. }
  1728. enableDebug=rulesData.enableDebug;
  1729. storage.getItem("forceState_"+location.host, v=>{
  1730. storage.getItem("ruleLastUpdate", date=>{
  1731. if(typeof(v)=="undefined"){
  1732. v=(rulesData.enableWhiteList?1:0);
  1733. }
  1734. forceState=v;
  1735. updateDate=date;
  1736. if(initConfig())return;
  1737. if(forceState==1)return;
  1738. let now=new Date().getTime();
  1739. if(!date || now-date>2*24*60*60*1000){
  1740. //storage.setItem("ruleLastUpdate", now);
  1741. updateRules(()=>{
  1742. //callback();
  1743. },(rule,err)=>{});
  1744. }
  1745. callback();
  1746. });
  1747. });
  1748. });
  1749. });
  1750. }
  1751.  
  1752. function requestDoc(url, callback){
  1753. _GM_xmlhttpRequest({
  1754. url: url,
  1755. method: 'GET',
  1756. overrideMimeType: 'text/html;charset='+document.charset,
  1757. headers: {
  1758. 'Referer': location.href
  1759. },
  1760. timeout: 5000,
  1761. onload: function(res) {
  1762. var doc=null;
  1763. try {
  1764. doc=document.implementation.createHTMLDocument('');
  1765. doc.documentElement.innerHTML=res.response;
  1766. }
  1767. catch (e) {
  1768. debug('parse error'+e.toString());
  1769. }
  1770. let pageElement=ruleParser.getPageElement(doc);
  1771. //只有1的話怕不是圖片哦
  1772. if(pageElement && (pageElement.length>1 || (pageElement.length==1 && pageElement[0].tagName!="IMG") )){
  1773. let result=ruleParser.insertPage(doc, pageElement, url, callback, false);
  1774. if(!result){
  1775. ruleParser.curSiteRule.action=1;
  1776. requestFromIframe(url, (doc, eles)=>{
  1777. loadPageOver();
  1778. if(eles){
  1779. ruleParser.insertPage(doc, eles, url, callback, true);
  1780. }
  1781. });
  1782. }
  1783. }else if(ruleParser.curSiteRule.singleUrl){
  1784. ruleParser.curSiteRule.action=1;
  1785. requestFromIframe(url, (doc, eles)=>{
  1786. loadPageOver();
  1787. if(eles){
  1788. ruleParser.insertPage(doc, eles, url, callback, true);
  1789. }
  1790. });
  1791. }else{
  1792. isPause=true;
  1793. callback(false);
  1794. }
  1795. },
  1796. onerror: function(e){
  1797. debug(e);
  1798. callback(false);
  1799. },
  1800. ontimeout: function(e){
  1801. debug(e);
  1802. callback(false);
  1803. }
  1804. });
  1805. }
  1806.  
  1807. var failFromIframe=0;
  1808. function requestFromIframe(url, callback){
  1809. let orgPage,curPage;
  1810. let iframe = document.createElement('iframe');
  1811. iframe.name = 'pagetual-iframe';
  1812. iframe.width = '100%';
  1813. iframe.height = '0';
  1814. iframe.frameBorder = '0';
  1815. if(ruleParser.curSiteRule.sandbox!=false){
  1816. iframe.sandbox="allow-same-origin allow-scripts allow-popups allow-forms";
  1817. }
  1818. iframe.style.cssText = 'margin:0!important;padding:0!important;visibility:hidden!important;';
  1819. iframe.addEventListener("load", e=>{
  1820. let waitTime=500,checkEval;
  1821. if(ruleParser.curSiteRule.wait){
  1822. if(isNaN(ruleParser.curSiteRule.wait)){
  1823. try{
  1824. checkEval=Function("doc",'"use strict";' + ruleParser.curSiteRule.wait);
  1825. }catch(e){
  1826. debug(e);
  1827. }
  1828. }else{
  1829. waitTime=ruleParser.curSiteRule.wait;
  1830. }
  1831. }
  1832. setTimeout(()=>{
  1833. let tryTimes=0;
  1834. function checkIframe(){
  1835. try{
  1836. let doc=iframe.contentDocument || iframe.contentWindow.document;
  1837. let eles=ruleParser.getPageElement(doc, iframe.contentWindow);
  1838. if(eles && eles.length>0 && (!checkEval || checkEval(doc))){
  1839. callback(doc, eles);
  1840. }else if(tryTimes++ < 10){
  1841. setTimeout(()=>{
  1842. checkIframe();
  1843. },waitTime);
  1844. return;
  1845. }else{
  1846. if(failFromIframe++ > 2){
  1847. failFromIframe=0;
  1848. debug("Stop as failFromIframe");
  1849. isPause=true;
  1850. callback(false, false);
  1851. }else{
  1852. callback(false, false);
  1853. }
  1854. }
  1855. }catch(e){
  1856. debug("Stop as cors");
  1857. //isPause=true;
  1858. ruleParser.curSiteRule.pageElement=allOfBody;
  1859. ruleParser.curSiteRule.action=0;
  1860. ruleParser.getInsert(true);
  1861. ruleParser.nextLinkHref=url;
  1862. callback(false, false);
  1863. }
  1864. document.body.removeChild(iframe);
  1865. }
  1866. checkIframe();
  1867. },waitTime);
  1868. });
  1869. iframe.src=url;
  1870. document.body.appendChild(iframe);
  1871. }
  1872.  
  1873. function initPage(){
  1874. ruleParser.initPage(()=>{
  1875. if(ruleParser.nextLinkHref){
  1876. initView();
  1877. let isJs=/^(javascript|#)/.test(ruleParser.nextLinkHref.replace(location.href,""));
  1878. if(!isJs){
  1879. _GM_registerMenuCommand(i18n(forceState==2?"cancelForceIframe":"forceIframe"), ()=>{
  1880. storage.setItem("forceState_"+location.host, (forceState==2?"":2));
  1881. location.reload();
  1882. });
  1883. }
  1884. _GM_registerMenuCommand(i18n("loadNow"), ()=>{
  1885. let loadNum=window.prompt(i18n("loadConfirm"), "1");
  1886. if(loadNum==="" || loadNum===null)return;
  1887. autoLoadNum=Math.abs(parseInt(loadNum));
  1888. nextPage();
  1889. });
  1890. }
  1891. initListener();
  1892. if(rulesData.initRun && ruleParser.curSiteRule.initRun!=0)nextPage();
  1893. });
  1894. }
  1895.  
  1896. function initView(){
  1897. _GM_addStyle(`
  1898. .pagetual_pageBar.stop {
  1899. -webkit-filter: invert(100%);
  1900. filter: invert(100%);
  1901. opacity: 1!important;
  1902. }
  1903. .pagetual_pageBar.hide {
  1904. display: none!important;
  1905. }
  1906. .pagetual_pageBar:hover {
  1907. opacity: 1!important;
  1908. }
  1909. .pagetual_pageBar span {
  1910. vertical-align: super;
  1911. }
  1912.  
  1913. .pagetual_pageBar span>svg:hover {
  1914. animation: touhouAni 1s infinite;
  1915. }
  1916. .pagetual_pageBar .pagetual_pageNum{
  1917. color: #55555f;
  1918. }
  1919. .pagetual_pageBar .pagetual_pageNum:hover{
  1920. color: #ff6464;
  1921. }
  1922.  
  1923. @keyframes touhouAni{
  1924. from {transform: rotate(0deg) scale3d(1.2, 1.2, 1.2);}
  1925. to {transform: rotate(360deg);}
  1926. }
  1927. @-webkit-keyframes touhouAni{
  1928. from {transform: rotate(0deg) scale3d(1.2, 1.2, 1.2);}
  1929. to {transform: rotate(360deg);}
  1930. }
  1931. `);
  1932. 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;`;
  1933. }
  1934. var loadingDiv=document.createElement("div");
  1935. loadingDiv.className="pagetual_loading";
  1936. 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;";
  1937. 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>`;
  1938.  
  1939. 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>`;
  1940. 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>`;
  1941. var pageBarStyle;
  1942. 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;`;
  1943. 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);`;
  1944.  
  1945. var isPause=false,isLoading=false,curPage=1,forceState=0,bottomGap=1000,autoLoadNum=-1;
  1946.  
  1947. function changeStop(stop, hide){
  1948. isPause=stop;
  1949. [].forEach.call(document.querySelectorAll(".pagetual_pageBar"), bar=>{
  1950. if(isPause){
  1951. bar.classList.add("stop");
  1952. if(hide)bar.classList.add("hide");
  1953. }else{
  1954. bar.classList.remove("stop");
  1955. if(hide)bar.classList.remove("hide");
  1956. }
  1957. });
  1958. }
  1959.  
  1960. function isInViewPort(element) {
  1961. if(!element.parentNode)return false;
  1962. if(_unsafeWindow.getComputedStyle(element).display=="none")return false;
  1963. const viewWidth = window.innerWidth || document.documentElement.clientWidth;
  1964. const viewHeight = window.innerHeight || document.documentElement.clientHeight;
  1965. const {
  1966. top,
  1967. right,
  1968. bottom,
  1969. left,
  1970. } = element.getBoundingClientRect();
  1971.  
  1972. return (
  1973. top >= 0 &&
  1974. left >= 0 &&
  1975. right <= viewWidth &&
  1976. bottom <= viewHeight
  1977. );
  1978. }
  1979.  
  1980. var urlChanged=false;
  1981. var _wr = function(type) {
  1982. var orig = history[type];
  1983. return function() {
  1984. var rv = orig.apply(this, arguments);
  1985. var e = new Event(type);
  1986. e.arguments = arguments;
  1987. window.dispatchEvent(e);
  1988. return rv;
  1989. };
  1990. };
  1991. history.pushState = _wr('pushState');
  1992. window.addEventListener('pushState', function(e) {
  1993. urlChanged=true;
  1994. isPause=true;
  1995. setTimeout(()=>{
  1996. if(location.href==configPage){
  1997. location.reload();
  1998. }
  1999. },1);
  2000. });
  2001.  
  2002. function initListener(){
  2003. let loadmoreBtn,loading=true;
  2004. setTimeout(()=>{
  2005. loadmoreBtn=getLoadMore(document);
  2006. if(loadmoreBtn && isVisible(loadmoreBtn, _unsafeWindow)){
  2007. loading=false;
  2008. }
  2009. },500);
  2010. let checkScrollReach=()=>{
  2011. let scrolly=window.scrollY;
  2012. let windowHeight=window.innerHeight || document.documentElement.clientHeight;
  2013. let scrollH=Math.max(document.documentElement.scrollHeight, document.body.scrollHeight);
  2014. if(scrollH-scrolly-windowHeight<bottomGap){
  2015. nextPage();
  2016. }
  2017. };
  2018. document.addEventListener('scroll', e=>{
  2019. if(urlChanged){
  2020. ruleParser.initPage(()=>{
  2021. if(ruleParser.nextLinkHref)initView();
  2022. });
  2023. urlChanged=false;
  2024. isPause=false;
  2025. }
  2026. if(isPause)return;
  2027. if(!loading){
  2028. loading=true;
  2029. setTimeout(()=>{loading=false},200);
  2030. if(!loadmoreBtn || !loadmoreBtn.parentNode){
  2031. loadmoreBtn=getLoadMore(document);
  2032. }
  2033. if(loadmoreBtn){
  2034. if(isInViewPort(loadmoreBtn)){
  2035. emuClick(loadmoreBtn);
  2036. }
  2037. }
  2038. }
  2039. setTimeout(()=>{
  2040. if(!isLoading){
  2041. checkScrollReach();
  2042. }
  2043. },100);
  2044. }, true);
  2045. document.addEventListener('dblclick', e=>{
  2046. if(rulesData.dbClick2Stop){
  2047. setTimeout(()=>{
  2048. changeStop(!isPause, rulesData.hideBar);
  2049. if(!isPause){
  2050. checkScrollReach();
  2051. }
  2052. },200);
  2053. }
  2054. });
  2055. }
  2056.  
  2057. function getLoadMore(doc){
  2058. if(ruleParser.curSiteRule.loadMore==="")return null;
  2059. let btnSel=ruleParser.curSiteRule.loadMore||".LoadMore,.load-more";
  2060. let loadmoreBtn=doc.querySelector(btnSel);
  2061. if(!loadmoreBtn){
  2062. let buttons=doc.querySelectorAll("input,button,a,div[onclick]"),loadmoreReg=/^\s*(加载更多|加載更多|load\s*more|もっと読み込む)\s*$/i;
  2063. for(let i=0;i<buttons.length;i++){
  2064. let button=buttons[i];
  2065. if(button && loadmoreReg.test(button.innerText)){
  2066. loadmoreBtn=button;
  2067. break;
  2068. }
  2069. }
  2070. }
  2071. return loadmoreBtn;
  2072. }
  2073.  
  2074. var hasPageNum=true;
  2075. function createPageBar(url){
  2076. let insert=ruleParser.getInsert();
  2077. if(!insert || !insert.parentNode)return;
  2078. curPage++;
  2079. if(rulesData.opacity==0)return;
  2080. let example=ruleParser.curSiteRule.insertPos==2?insert.children[0]:(insert.previousElementSibling||insert);
  2081. if(!example || !example.parentNode)example=insert;
  2082. let inTable=example.parentNode.tagName=="TABLE" ||
  2083. example.tagName=="TR" ||
  2084. example.tagName=="TBODY" ||
  2085. (example.previousElementSibling && example.previousElementSibling.tagName=="TR") ||
  2086. (example.previousElementSibling && example.previousElementSibling.tagName=="TBODY");
  2087. let inLi=example.tagName=="LI" || (example.previousElementSibling && example.previousElementSibling.tagName=="LI");
  2088. let pageBar=document.createElement(inTable?"tr":(inLi?"li":"div"));
  2089. let upSpan=document.createElement("span");
  2090. let downSpan=document.createElement("span");
  2091. let pageText=document.createElement("a");
  2092. let pageNum;
  2093. pageBar.className="pagetual_pageBar";
  2094. pageBar.id="pagetual_pageBar";
  2095. if(isPause){
  2096. pageBar.classList.add("stop");
  2097. }
  2098. pageBar.style.cssText=pageBarStyle;
  2099. pageBar.title=i18n(isPause?"enable":"disable");
  2100. upSpan.innerHTML=upSvg;
  2101. upSpan.title=i18n("toTop");
  2102. downSpan.innerHTML=downSvg;
  2103. downSpan.title=i18n("toBottom");
  2104. upSpan.style.cssText=initStyle;
  2105. downSpan.style.cssText=initStyle;
  2106. pageText.href=url;
  2107. pageText.style.cssText=pageTextStyle;
  2108. pageText.title=i18n("current");
  2109. pageBar.appendChild(upSpan);
  2110. pageBar.appendChild(pageText);
  2111. if(ruleParser.curSiteRule.pageNum || (hasPageNum && /[&\/\?](p=|page[=\/])\d+/.test(url))){
  2112. pageText.innerHTML="Page ";
  2113. pageNum=document.createElement("span");
  2114. pageNum.innerText=curPage;
  2115. pageNum.className="pagetual_pageNum";
  2116. pageNum.title=i18n("inputPageNum");
  2117. pageNum.style.cssText=pageTextStyle;
  2118. pageNum.style.cursor="pointer";
  2119. pageNum.style.color="";
  2120. pageNum.addEventListener("click", e=>{
  2121. let pageInput=prompt(i18n("inputPageNum"), "1");
  2122. if(pageInput){
  2123. let pageLink=ruleParser.getLinkByPage(url, pageInput);
  2124. if(pageLink){
  2125. _GM_openInTab(pageLink,{active:true});
  2126. }
  2127. }
  2128. e.preventDefault();
  2129. e.stopPropagation();
  2130. });
  2131. pageBar.appendChild(pageNum);
  2132. }else{
  2133. pageText.innerHTML="Page "+curPage;
  2134. hasPageNum=false;
  2135. }
  2136. pageBar.appendChild(downSpan);
  2137. let parentStyle=_unsafeWindow.getComputedStyle(example.parentNode);
  2138. pageBar.style.width=parseInt(parentStyle.width)-10+"px";
  2139. if(parentStyle.display=="grid" || parentStyle.display=="inline-grid"){
  2140. pageBar.style.gridColumnStart=1;
  2141. pageBar.style.gridColumnEnd=1+parseInt(example.parentNode.offsetWidth/example.offsetWidth);
  2142. }
  2143. if(inTable){
  2144. example=(example.tagName=="TR" || example.tagName=="TBODY")?example:example.previousElementSibling;
  2145. if(example.previousElementSibling)example=example.previousElementSibling;
  2146. let tdNum=0;
  2147. [].forEach.call(example.querySelectorAll("td,th"), td=>{
  2148. tdNum+=td.colSpan||1;
  2149. });
  2150. pageBar.style.display="table-row";
  2151. pageBar.style.backgroundColor="unset";
  2152. let td=document.createElement("td");
  2153. td.style.backgroundColor="rgb(240 240 240 / 80%)";
  2154. td.style.borderRadius="20px";
  2155. td.colSpan=tdNum||1;
  2156. td.style.padding="0 0";
  2157. td.style.textAlign="center";
  2158. td.appendChild(upSpan);
  2159. td.appendChild(pageText);
  2160. if(pageNum)td.appendChild(pageNum);
  2161. td.appendChild(downSpan);
  2162. pageBar.appendChild(td);
  2163. }else if(inLi){
  2164. example=example.tagName=="LI"?example:example.previousElementSibling;
  2165. pageBar.style.display="table-row";
  2166. pageBar.style.backgroundColor="unset";
  2167. let td=document.createElement("td");
  2168. td.style.backgroundColor="rgb(240 240 240 / 80%)";
  2169. td.style.borderRadius="20px";
  2170. td.colSpan=example.children.length;
  2171. td.style.padding="0 0";
  2172. td.style.textAlign="center";
  2173. td.style.minWidth="150px";
  2174. td.appendChild(upSpan);
  2175. td.appendChild(pageText);
  2176. td.style.width=pageBar.style.width;
  2177. if(pageNum)td.appendChild(pageNum);
  2178. td.appendChild(downSpan);
  2179. pageBar.appendChild(td);
  2180. }
  2181.  
  2182. upSpan.addEventListener("click", e=>{
  2183. document.body.scrollTop=0;
  2184. document.documentElement.scrollTop=0;
  2185. e.preventDefault();
  2186. e.stopPropagation();
  2187. });
  2188. downSpan.addEventListener("click", e=>{
  2189. changeStop(true);
  2190. pageBar.title=i18n(isPause?"enable":"disable");
  2191. document.body.scrollTop=9999999;
  2192. document.documentElement.scrollTop=9999999;
  2193. e.preventDefault();
  2194. e.stopPropagation();
  2195. });
  2196. pageBar.addEventListener("click", e=>{
  2197. changeStop(!isPause);
  2198. pageBar.title=i18n(isPause?"enable":"disable");
  2199. });
  2200. pageText.addEventListener("click", e=>{
  2201. e.stopPropagation();
  2202. });
  2203. if(ruleParser.curSiteRule.insertPos==2){
  2204. insert.appendChild(pageBar);
  2205. }else{
  2206. insert.parentNode.insertBefore(pageBar, insert);
  2207. }
  2208. if(ruleParser.curSiteRule.pageBar){
  2209. try{
  2210. Function("pageBar",'"use strict";' + ruleParser.curSiteRule.pageBar)(pageBar);
  2211. }catch(e){
  2212. debug(e);
  2213. }
  2214. }
  2215.  
  2216. let scrollH=Math.max(document.documentElement.scrollHeight, document.body.scrollHeight);
  2217. let posEle=pageBar.nextElementSibling||pageBar;
  2218. while(posEle && !posEle.offsetParent){
  2219. posEle=posEle.previousElementSibling||posEle.parentNode;
  2220. }
  2221. if(posEle){
  2222. let actualTop = posEle.offsetTop;
  2223. let current = posEle.parentNode.offsetParent;
  2224. while (current !== null){
  2225. actualTop += current.offsetTop;
  2226. current = current.offsetParent;
  2227. }
  2228. bottomGap=scrollH-actualTop+(window.innerHeight||document.documentElement.clientHeight)*(ruleParser.curSiteRule.rate||1);
  2229. if(bottomGap<100)bottomGap=100;
  2230. }else{
  2231. bottomGap=1000;
  2232. }
  2233. return pageBar;
  2234. }
  2235.  
  2236. function emuClick(btn){
  2237. if(!PointerEvent)return btn.click();
  2238. let eventParam={
  2239. isTrusted: true,
  2240. altKey: false,
  2241. azimuthAngle: 0,
  2242. bubbles: true,
  2243. button: 0,
  2244. buttons: 0,
  2245. clientX: 1,
  2246. clientY: 1,
  2247. cancelBubble: false,
  2248. cancelable: true,
  2249. composed: true,
  2250. ctrlKey: false,
  2251. defaultPrevented: false,
  2252. detail: 1,
  2253. eventPhase: 2,
  2254. fromElement: null,
  2255. height: 1,
  2256. isPrimary: false,
  2257. metaKey: false,
  2258. pointerId: 1,
  2259. pointerType: "mouse",
  2260. pressure: 0,
  2261. relatedTarget: null,
  2262. returnValue: true,
  2263. shiftKey: false,
  2264. toElement: null,
  2265. twist: 0,
  2266. type: "click",
  2267. which: 1
  2268. };
  2269. var mouseclick = new PointerEvent("click",eventParam);
  2270. btn.dispatchEvent(mouseclick);
  2271. }
  2272.  
  2273. var emuIframe;
  2274. function emuPage(callback){
  2275. let orgPage,curPage,iframeDoc,times=0,loadmoreBtn,loadmoreEnd=false,waitTimes=10;
  2276. function checkPage(){
  2277. if(isPause)return;
  2278. try{
  2279. iframeDoc=emuIframe.contentDocument || emuIframe.contentWindow.document;
  2280. }catch(e){
  2281. debug("Stop as cors");
  2282. isPause=true;
  2283. callback(false, false);
  2284. return;
  2285. }
  2286.  
  2287. let nextLink=ruleParser.getNextLink(iframeDoc);
  2288. let waitTime=500,checkEval;
  2289. if(ruleParser.curSiteRule.wait){
  2290. if(isNaN(ruleParser.curSiteRule.wait)){
  2291. try{
  2292. checkEval=Function("doc",'"use strict";' + ruleParser.curSiteRule.wait);
  2293. }catch(e){
  2294. debug(e);
  2295. }
  2296. }else{
  2297. waitTime=ruleParser.curSiteRule.wait;
  2298. }
  2299. }
  2300.  
  2301. if(!orgPage){
  2302. if(!loadmoreEnd){
  2303. loadmoreBtn=getLoadMore(iframeDoc);
  2304. if(loadmoreBtn && isVisible(loadmoreBtn, iframeDoc.defaultView)){
  2305. emuClick(loadmoreBtn);
  2306. let intv=setInterval(()=>{
  2307. loadmoreBtn=getLoadMore(iframeDoc);
  2308. if(!loadmoreBtn || !loadmoreBtn.parentNode || !isVisible(loadmoreBtn, iframeDoc.defaultView)){
  2309. clearInterval(intv);
  2310. loadmoreEnd=true;
  2311. setTimeout(()=>{
  2312. checkPage();
  2313. },500);
  2314. }else{
  2315. emuClick(loadmoreBtn);
  2316. }
  2317. },200);
  2318. return;
  2319. }else{
  2320. loadmoreEnd=true;
  2321. }
  2322. }
  2323. let pageEle=ruleParser.getPageElement(iframeDoc, iframeDoc.defaultView, true);
  2324. if(!nextLink || !pageEle || (checkEval && !checkEval(iframeDoc))){
  2325. if(ruleParser.curSiteRule.wait && waitTimes-->0){
  2326. setTimeout(()=>{
  2327. checkPage();
  2328. },waitTime);
  2329. return;
  2330. }
  2331. }
  2332. orgPage=pageEle;
  2333. if(!orgPage || orgPage.length==0){
  2334. debug("Stop as no page when emu");
  2335. isPause=true;
  2336. callback(false, false);
  2337. return;
  2338. }
  2339. if(orgPage && orgPage[0].tagName=="UL")orgPage=orgPage[0].children;
  2340. if(orgPage && nextLink){
  2341. orgPage=orgPage[parseInt(orgPage.length/2)];
  2342. if(!isVisible(nextLink, iframeDoc.defaultView)){
  2343. debug("Stop as next hide when emu");
  2344. isPause=true;
  2345. callback(false, false);
  2346. }else{
  2347. emuClick(nextLink);
  2348. setTimeout(()=>{
  2349. checkPage();
  2350. },500);
  2351. }
  2352. }else{
  2353. debug("Stop as no next when emu");
  2354. isPause=true;
  2355. callback(false, false);
  2356. }
  2357. return;
  2358. }
  2359. if(times++ > 20){
  2360. //emuClick(nextLink);
  2361. debug("Stop as timeout when emu");
  2362. isPause=true;
  2363. callback(false, false);
  2364. return;
  2365. }
  2366. let eles=ruleParser.getPageElement(iframeDoc, iframeDoc.defaultView, true),checkItem=eles;
  2367. if(eles && eles.length>0 && eles[0].tagName=="UL")checkItem=eles[0].children;
  2368. if(!eles || eles.length==0 || orgPage == checkItem[parseInt(checkItem.length/2)] || (checkEval && !checkEval(iframeDoc))){
  2369. setTimeout(()=>{
  2370. checkPage();
  2371. },waitTime);
  2372. }else{
  2373. callback(iframeDoc, eles);
  2374. }
  2375. }
  2376. if(!emuIframe){
  2377. emuIframe = document.createElement('iframe');
  2378. emuIframe.name = 'pagetual-iframe';
  2379. if(ruleParser.curSiteRule.sandbox!=false){
  2380. emuIframe.sandbox="allow-same-origin allow-scripts allow-popups allow-forms";
  2381. }
  2382. emuIframe.width = '100%';
  2383. emuIframe.height = '0';
  2384. emuIframe.frameBorder = '0';
  2385. emuIframe.style.cssText = 'margin:0!important;padding:0!important;visibility:hidden!important;';
  2386. emuIframe.addEventListener("load", e=>{
  2387. setTimeout(()=>{
  2388. try{
  2389. iframeDoc=emuIframe.contentDocument || emuIframe.contentWindow.document;
  2390. }catch(e){
  2391. debug("Stop as cors");
  2392. isPause=true;
  2393. callback(false, false);
  2394. return;
  2395. }
  2396. let code=ruleParser.curSiteRule.init;
  2397. if(code){
  2398. try{
  2399. Function('doc','win','"use strict";' + code)(iframeDoc, iframeDoc.defaultView);
  2400. }catch(e){
  2401. debug(e);
  2402. }
  2403. }
  2404. checkPage();
  2405. },500);
  2406. });
  2407. emuIframe.src=location.href;
  2408. document.body.appendChild(emuIframe);
  2409. }else{
  2410. checkPage();
  2411. }
  2412. }
  2413.  
  2414. function forceIframe(url, callback){
  2415. let curIframe = document.createElement('iframe'),iframeDoc;
  2416. curIframe.name = 'pagetual-iframe';
  2417. curIframe.sandbox="allow-same-origin allow-scripts allow-popups allow-forms";
  2418. curIframe.frameBorder = '0';
  2419. curIframe.scrolling="no";
  2420. 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;';
  2421. curIframe.addEventListener("load", e=>{
  2422. try{
  2423. iframeDoc=curIframe.contentDocument || curIframe.contentWindow.document;
  2424. }catch(e){
  2425. debug("Stop as cors");
  2426. isPause=true;
  2427. callback(false, false);
  2428. return;
  2429. }
  2430. ruleParser.insertPage(iframeDoc, [], url, null, true);
  2431. callback(curIframe, true);
  2432. curIframe.style.height=iframeDoc.body.scrollHeight+"px";
  2433. curIframe.style.width=iframeDoc.body.scrollWidth+"px";
  2434. });
  2435. let inAction=false;
  2436. let forceRefresh=e=>{
  2437. if(inAction || !iframeDoc)return;
  2438. inAction=true;
  2439. setTimeout(()=>{
  2440. inAction=false;
  2441. curIframe.style.height=iframeDoc.body.scrollHeight+"px";
  2442. curIframe.style.width=iframeDoc.body.scrollWidth+"px";
  2443. if(!ruleParser.nextLinkHref){
  2444. ruleParser.getNextLink(iframeDoc);
  2445. if(ruleParser.nextLinkHref){
  2446. document.removeEventListener("scroll", forceRefresh);
  2447. }
  2448. }else{
  2449. document.removeEventListener("scroll", forceRefresh);
  2450. }
  2451. },500);
  2452. curIframe.style.height=iframeDoc.body.scrollHeight+"px";
  2453. curIframe.style.width=iframeDoc.body.scrollWidth+"px";
  2454. };
  2455. document.addEventListener("scroll", forceRefresh);
  2456. curIframe.src=url;
  2457. let insert=ruleParser.getInsert();
  2458. document.body.appendChild(curIframe);
  2459. return curIframe;
  2460. }
  2461.  
  2462. function loadPageOver(){
  2463. isLoading=false;
  2464. if(loadingDiv.parentNode){
  2465. loadingDiv.parentNode.removeChild(loadingDiv);
  2466. }
  2467. setTimeout(()=>{
  2468. let scrollH=Math.max(document.documentElement.scrollHeight, document.body.scrollHeight);
  2469. if(scrollH < (window.innerHeight || document.documentElement.clientHeight)){
  2470. nextPage();
  2471. }
  2472. },1);
  2473. }
  2474.  
  2475. function nextPage(){
  2476. if(isPause || isLoading)return;
  2477. let nextLink=ruleParser.nextLinkHref;
  2478. if(!nextLink)return;
  2479. let insert=ruleParser.getInsert();
  2480. if(insert){
  2481. let isJs=/^(javascript|#)/.test(nextLink.replace(location.href,""));
  2482. if(location.protocol=="https:" && /^http:/.test(nextLink)){
  2483. nextLink=nextLink.replace(/^http/,"https");
  2484. }
  2485. isLoading=true;
  2486. document.body.appendChild(loadingDiv);
  2487. let sleep=ruleParser.curSiteRule.sleep||0;
  2488. setTimeout(()=>{
  2489. if(ruleParser.curSiteRule.pageElementByJs){
  2490. var over=ele=>{
  2491. loadPageOver();
  2492. if(ele){
  2493. createPageBar(nextLink);
  2494. ruleParser.insertPage(null, ele, nextLink, null, true);
  2495. if(autoLoadNum>=0){
  2496. if(autoLoadNum!=0 && --autoLoadNum==0){
  2497. autoLoadNum=-1;
  2498. }else{
  2499. nextPage();
  2500. }
  2501. }
  2502. }else{
  2503. debug("Stop as no page when get by js");
  2504. isPause=true;
  2505. }
  2506. };
  2507. try{
  2508. Function("over",'"use strict";' + ruleParser.curSiteRule.pageElementByJs)(over);
  2509. }catch(e){
  2510. debug(e);
  2511. }
  2512. }else if(ruleParser.curSiteRule.action==1 && !isJs){
  2513. requestFromIframe(nextLink, (doc, eles)=>{
  2514. loadPageOver();
  2515. if(eles){
  2516. createPageBar(nextLink);
  2517. ruleParser.insertPage(doc, eles, nextLink, null, true);
  2518. if(autoLoadNum>=0){
  2519. if(autoLoadNum!=0 && --autoLoadNum==0){
  2520. autoLoadNum=-1;
  2521. }else{
  2522. nextPage();
  2523. }
  2524. }
  2525. }
  2526. });
  2527. }else if((forceState==2||ruleParser.curSiteRule.action==2) && !isJs){
  2528. forceIframe(nextLink, (iframe, eles)=>{
  2529. loadPageOver();
  2530. let pageBar=createPageBar(nextLink);
  2531. iframe.parentNode.insertBefore(pageBar, iframe);
  2532. if(autoLoadNum>=0){
  2533. if(autoLoadNum!=0 && --autoLoadNum==0){
  2534. autoLoadNum=-1;
  2535. }else{
  2536. nextPage();
  2537. }
  2538. }
  2539. });
  2540. }else{
  2541. if(!isJs){
  2542. requestDoc(nextLink, (eles)=>{
  2543. loadPageOver();
  2544. if(eles){
  2545. createPageBar(nextLink);
  2546. if(autoLoadNum>=0){
  2547. if(autoLoadNum!=0 && --autoLoadNum==0){
  2548. autoLoadNum=-1;
  2549. }else{
  2550. nextPage();
  2551. }
  2552. }
  2553. }
  2554. });
  2555. }else{
  2556. emuPage((doc, eles)=>{
  2557. loadPageOver();
  2558. if(eles){
  2559. createPageBar(nextLink);
  2560. ruleParser.insertPage(doc, eles, "", null, true);
  2561. if(autoLoadNum>=0){
  2562. if(autoLoadNum!=0 && --autoLoadNum==0){
  2563. autoLoadNum=-1;
  2564. }else{
  2565. nextPage();
  2566. }
  2567. }
  2568. }
  2569. });
  2570. }
  2571. }
  2572. },sleep);
  2573. }
  2574. }
  2575.  
  2576. function init(){
  2577. initRules(()=>{
  2578. initPage();
  2579. });
  2580. }
  2581. setTimeout(()=>{
  2582. init();
  2583. },300);
  2584. })();