东方永页机

自动翻页脚本 - 自动加载并拼接下一分页内容,无需规则驱动支持任意网页

当前为 2022-05-28 提交的版本,查看 最新版本

  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.8.3
  14. // @description Perpetual pages - Most powerful Auto Pager script. Auto loading next paginated web pages and inserting into current page.
  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. // @match *://*/*
  26. // @license MIT
  27. // @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==
  28. // @grant GM_xmlhttpRequest
  29. // @grant GM_registerMenuCommand
  30. // @grant GM_notification
  31. // @grant GM_getValue
  32. // @grant GM_setValue
  33. // @grant GM_addStyle
  34. // @grant GM_openInTab
  35. // @grant GM_deleteValue
  36. // @grant GM.xmlHttpRequest
  37. // @grant GM.registerMenuCommand
  38. // @grant GM.notification
  39. // @grant GM.getValue
  40. // @grant GM.setValue
  41. // @grant GM.addStyle
  42. // @grant GM.openInTab
  43. // @grant GM.deleteValue
  44. // @supportURL https://github.com/hoothin/UserScripts/issues
  45. // @connect wedata.net
  46. // @connect githubusercontent.com
  47. // @run-at document-idle
  48. // @exclude http://www.toodledo.com/tasks/*
  49. // @exclude http*://maps.google.com*/*
  50. // @exclude *://www.google.*/_/chrome/newtab*
  51. // @exclude *://mega.*/*
  52. // @exclude *://*.mega.*/*
  53. // @exclude *://*.youku.com/v_*
  54. // @exclude *://*pan.baidu.com
  55. // @exclude *://*.iqiyi.com/v_*
  56. // @exclude *://*.iqiyi.com/w_*
  57. // @exclude *://*.iqiyi.com/a_*
  58. // @exclude *://*.le.com/ptv/vplay/*
  59. // @exclude *://v.qq.com/x/cover/*
  60. // @exclude *://v.qq.com/x/page/*
  61. // @exclude *://v.qq.com/tv/*
  62. // @exclude *://*.tudou.com/listplay/*
  63. // @exclude *://*.tudou.com/albumplay/*
  64. // @exclude *://*.tudou.com/programs/view/*
  65. // @exclude *://*.mgtv.com/b/*
  66. // @exclude *://film.sohu.com/album/*
  67. // @exclude *://tv.sohu.com/v/*
  68. // @exclude *://*.bilibili.com/video/*
  69. // @exclude *://*.bilibili.com/bangumi/play/*
  70. // @exclude *://*.baofeng.com/play/*
  71. // @exclude *://vip.pptv.com/show/*
  72. // @exclude *://v.pptv.com/show/*
  73. // @exclude *://www.le.com/ptv/vplay/*
  74. // @exclude *://www.wasu.cn/Play/show/*
  75. // @exclude *://m.v.qq.com/*
  76. // @exclude *://m.iqiyi.com/*
  77. // @exclude *://m.youku.com/alipay_video/*
  78. // @exclude *://m.mgtv.com/b/*
  79. // @exclude *://m.tv.sohu.com/v/*
  80. // @exclude *://m.film.sohu.com/album/*
  81. // @exclude *://m.le.com/ptv/vplay/*
  82. // @exclude *://m.pptv.com/show/*
  83. // @exclude *://m.acfun.cn/v/*
  84. // @exclude *://m.bilibili.com/video/*
  85. // @exclude *://m.bilibili.com/anime/*
  86. // @exclude *://m.bilibili.com/bangumi/play/*
  87. // @exclude *://m.wasu.cn/Play/show/*
  88. // @exclude *://www.youtube.com
  89. // @exclude *://www.youtube.com/
  90. // @exclude *://www.youtube.com/watch*
  91. // @exclude *://baike.baidu.com/*
  92. // @exclude *://*.instagram.com/*
  93. // @exclude *://order.jd.com/*
  94. // @exclude *://pagetual.hoothin.com/*
  95. // @exclude *://hoothin.github.io/PagetualGuide/*
  96. // @exclude *://wenku.baidu.com/view/*
  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. let config={};
  128. switch (lang){
  129. case "zh-CN":
  130. case "zh-SG":
  131. config={
  132. enableDebug:"调试模式,输出信息至控制台",
  133. disable:"暂时禁用",
  134. disableSite:"在此站禁用",
  135. enable:"启用翻页",
  136. toTop:"回到顶部",
  137. toBottom:"前往页尾",
  138. current:"当前页",
  139. forceIframe:"强制拼接",
  140. cancelForceIframe:"取消强制拼接",
  141. configure:"打开配置页",
  142. firstUpdate:"点击此处初始化规则",
  143. update:"更新规则",
  144. click2update:"点击立即更新规则",
  145. loadNow:"立即翻页",
  146. loadConfirm:"要翻几页?(0为不间断)",
  147. noNext:"没有找到下一页,请新建规则",
  148. passSec:"更新于 #t# 秒前",
  149. passMin:"更新于 #t# 分钟前",
  150. passHour:"更新于 #t# 小时前",
  151. passDay:"更新于 #t# 天前",
  152. cantDel:"无法删除内置规则",
  153. confirmDel:"是否确认要删除此规则?",
  154. updateSucc:"更新成功",
  155. beginUpdate:"正在更新,请稍候",
  156. customUrls:"导入规则url,一行一条,AutoPagerize 格式规则需要以\"0|\"开头",
  157. customRules:"输入【东方永页机】格式的自定义规则",
  158. save:"保存设置",
  159. loadingText:"少女祈祷中...",
  160. opacity:"分页隔条不透明值",
  161. hideBar:"空白处双击隐藏分页隔条",
  162. dbClick2Stop:"空白处双击暂停翻页",
  163. sortTitle:"排序在下次更新规则后生效",
  164. autoRun:"自动启用,否则为白名单模式",
  165. inputPageNum:"输入页码跳转",
  166. enableHistory:"翻页后写入历史记录",
  167. initRun:"打开页面后立即尝试翻页,否则滚动至页尾再翻页",
  168. preload:"翻页前预读下一页,加速浏览",
  169. click2ImportRule:"点击下方添加特殊规则库,添加后再行更新:",
  170. forceAllBody:"是否拼接整个页面?",
  171. openInNewTab:"使拼接页面的内容在新页面打开",
  172. importSucc:"导入成功",
  173. editCurrent:"自定义此站规则",
  174. editBlacklist:"编辑黑名单网址,一行一条,支持? *通配符",
  175. upBtnImg:"回到页首图标",
  176. downBtnImg:"前往页尾图标",
  177. dbClick2StopCtrl:"双击时需要按住 Ctrl 键",
  178. dbClick2StopAlt:"双击时需要按住 Alt 键",
  179. dbClick2StopShift:"双击时需要按住 Shift 键",
  180. dbClick2StopMeta:"双击时需要按住 Meta 键"
  181. };
  182. break;
  183. case "zh-TW":
  184. case "zh-HK":
  185. config={
  186. enableDebug:"調試模式,輸出信息至控制台",
  187. disable:"暫時禁用",
  188. disableSite:"在此站禁用",
  189. enable:"啟用翻頁",
  190. toTop:"回到頂部",
  191. toBottom:"前往頁尾",
  192. current:"當前頁",
  193. forceIframe:"強制拼接",
  194. cancelForceIframe:"取消强制拼接",
  195. configure:"打開配置頁",
  196. firstUpdate:"點擊此處初始化規則",
  197. update:"更新規則",
  198. click2update:"點擊立即更新規則",
  199. loadNow:"立即翻頁",
  200. loadConfirm:"要翻几頁?(0為不間斷)",
  201. noNext:"沒有找到下一頁,請新建規則",
  202. passSec:"更新于 #t# 秒前",
  203. passMin:"更新于 #t# 分鐘前",
  204. passHour:"更新于 #t# 小時前",
  205. passDay:"更新于 #t# 天前",
  206. cantDel:"無法刪除内置規則",
  207. confirmDel:"是否確認要刪除此規則?",
  208. updateSucc:"更新成功",
  209. beginUpdate:"正在更新,請稍候",
  210. customUrls:"導入規則url,一行一條,AutoPagerize 格式規則需要以\"0|\"開頭",
  211. customRules:"輸入【東方永頁機】格式的自定義規則",
  212. save:"存儲設置",
  213. loadingText:"少女祈禱中...",
  214. opacity:"分頁隔條不透明值",
  215. hideBar:"空白處雙擊隱藏分頁隔條",
  216. dbClick2Stop:"空白處雙擊暫停翻頁",
  217. sortTitle:"排序在下次更新規則後生效",
  218. autoRun:"自動啓用,否則為白名單模式",
  219. inputPageNum:"輸入頁碼跳轉",
  220. enableHistory:"翻頁后寫入歷史記錄",
  221. initRun:"打開頁面后立即嘗試翻頁,否則滾動至頁尾再翻頁",
  222. preload:"翻頁前預讀下一頁,加速瀏覽",
  223. click2ImportRule:"點擊下方添加特殊規則庫,添加後再行更新:",
  224. forceAllBody:"是否拼接整個頁面?",
  225. openInNewTab:"使拼接頁面的内容在新頁面打開",
  226. importSucc:"導入成功",
  227. editCurrent:"自定義此站規則",
  228. editBlacklist:"編輯黑名單網址,一行一條,支持? *通配符",
  229. upBtnImg:"回到頁首圖標",
  230. downBtnImg:"前往頁尾圖標",
  231. dbClick2StopCtrl:"雙擊時需要按住 Ctrl 鍵",
  232. dbClick2StopAlt:"雙擊時需要按住 Alt 鍵",
  233. dbClick2StopShift:"雙擊時需要按住 Shift 鍵",
  234. dbClick2StopMeta:"雙擊時需要按住 Meta 鍵"
  235. };
  236. break;
  237. case "ja":
  238. config = {
  239. enableDebug:"デバッグモード",
  240. disable: "一時的に無効にする",
  241. disableSite:"このサイト無効",
  242. enable: "ページめくりを有効にする",
  243. toTop: "トップに戻る",
  244. toBottom: "ページの下部に移動",
  245. current: "現在のページ",
  246. forceIframe: "強制ステッチ",
  247. cancelForceIframe: "強制ステッチをキャンセル",
  248. configure: "設定ページを開く",
  249. firstUpdate:"ここをクリックしてルールを初期化します",
  250. update: "更新ルール",
  251. click2update:"今すぐルールを更新してください",
  252. loadNow:"今すぐページをめくる",
  253. loadConfirm:"数ページめくりたいですか?(0は途切れない)",
  254. noNext:"次のページが見つかりません、新しいルールを作成してください",
  255. passSec: "#t#秒前に更新",
  256. passMin: "#t#分前に更新",
  257. passHour: "#t#時間前に更新",
  258. passDay: "#t#日前に更新",
  259. cantDel: "組み込みルールを削除できません",
  260. confirmDel: "このルールを削除してもよろしいですか?",
  261. updateSucc: "更新に成功しました",
  262. beginUpdate: "更新中、お待ちください",
  263. customUrls: "インポートルールのURL、1行に1つ、AutoPagerizeフォーマットルールは\"0|\"で始まる必要があります",
  264. customRules: "【東方永頁機】の形式でカスタムルールを入力してください",
  265. save: "設定を保存",
  266. loadingText: "少女祈祷中...",
  267. opacity:"ページネーションバーの不透明値",
  268. hideBar:"空白部分をダブルクリックして、ページ区切り文字を非表示にします",
  269. dbClick2Stop:"空白部分をダブルクリックしてページめくりを一時停止します",
  270. sortTitle:"並べ替えは、次のルールの更新後に有効になります",
  271. autoRun:"自動的に有効",
  272. inputPageNum:"ジャンプするページ番号を入力",
  273. enableHistory:"ページめくり後の履歴を書く",
  274. initRun:"Webページを開いた直後にページをめくる",
  275. preload:"事前に次のページを読む",
  276. click2ImportRule:"以下をクリックして、ルールベースを追加します:",
  277. forceAllBody:"フルページ埋め込み?",
  278. openInNewTab:"スプライスされたページのコンテンツを新しいページで開きます",
  279. importSucc:"インポート完了",
  280. editCurrent:"現在のルールの編集",
  281. editBlacklist:"ブラックリストのURLを編集し、1行ずつ、サポート? *ワイルドカード",
  282. upBtnImg:"トップアイコンに戻る",
  283. downBtnImg:"フッターアイコンに移動",
  284. dbClick2StopCtrl:"ダブルクリックするときにCtrlキーを押したままにする",
  285. dbClick2StopAlt:"ダブルクリックするときにAltキーを押したままにする",
  286. dbClick2StopShift:"ダブルクリックするときにShiftキーを押したままにする",
  287. dbClick2StopMeta:"ダブルクリックするときにMetaキーを押したままにする"
  288. };
  289. break;
  290. default:
  291. config={
  292. enableDebug:"Enable debug output",
  293. disable:"Disable",
  294. disableSite:"Disable on the site",
  295. enable:"Enable",
  296. toTop:"To Top",
  297. toBottom:"To Bottom",
  298. current:"Current Page",
  299. forceIframe:"Force to join",
  300. cancelForceIframe:"Cancel Force join",
  301. configure:"Configure",
  302. firstUpdate:"Click here to initialize the rules",
  303. update:"Update rules",
  304. click2update:"Click to update rules from url now",
  305. loadNow:"Load next now",
  306. loadConfirm:"How much pages do you want to load? (0 means infinite)",
  307. noNext:"No next link found, please create a new rule",
  308. passSec:"Updated #t# seconds ago",
  309. passMin:"Updated #t# minutes ago",
  310. passHour:"Updated #t# hours ago",
  311. passDay:"Updated #t# days ago",
  312. cantDel:"Can't delete buildin rules",
  313. confirmDel:"Are you sure you want to delete this rule?",
  314. updateSucc:"Update succeeded",
  315. beginUpdate:"Begin update, wait a minute please",
  316. customUrls:"Import rule url, One url per line, rules on AutoPagerize format need to start with \"0|\"",
  317. customRules:"Input custom rules with [Pagetual] format",
  318. save:"Save",
  319. loadingText:"Shojo Now Loading...",
  320. opacity:"Pagination spacer opacity",
  321. hideBar:"Double-click on the blank space to hide the paging spacer",
  322. dbClick2Stop:"Double-click on the blank space to pause",
  323. sortTitle:"Sorting takes effect after the next rule update",
  324. autoRun:"Auto run (black list mode)",
  325. inputPageNum:"Enter page number to jump",
  326. enableHistory:"Write history after page turning",
  327. initRun:"Turn pages immediately after opening",
  328. preload:"Preload next page for speeding up",
  329. click2ImportRule:"Click to import base rules link, then click to update rules:",
  330. forceAllBody:"Join full body of page?",
  331. openInNewTab:"Open urls of additions in new tab",
  332. importSucc:"Import completed",
  333. editCurrent:"Edit rule for current",
  334. editBlacklist:"Edit the blacklist urls, line by line, Support ? * for wildcard",
  335. upBtnImg:"Icon of back to top",
  336. downBtnImg:"Icon of go to footer",
  337. dbClick2StopCtrl:"Press and hold the Ctrl key when double-clicking",
  338. dbClick2StopAlt:"Press and hold the Alt key when double-clicking",
  339. dbClick2StopShift:"Press and hold the Shift key when double-clicking",
  340. dbClick2StopMeta:"Press and hold the Meta key when double-clicking"
  341. };
  342. break;
  343. }
  344. var i18n=(name, param)=>{
  345. return config[name]?config[name].replace("#t#",param):name;
  346. };
  347.  
  348. var noRuleTest=false;
  349. var enableDebug=true;
  350. var debug=str=>{
  351. if(enableDebug){
  352. console.debug(str);
  353. }
  354. };
  355.  
  356. var _GM_xmlhttpRequest,_GM_registerMenuCommand,_GM_notification,_GM_addStyle,_GM_openInTab;
  357. if(typeof GM_xmlhttpRequest!='undefined'){
  358. _GM_xmlhttpRequest=GM_xmlhttpRequest;
  359. }else if(typeof GM!='undefined' && typeof GM.xmlHttpRequest!='undefined'){
  360. _GM_xmlhttpRequest=GM.xmlHttpRequest;
  361. }else{
  362. _GM_xmlhttpRequest=(f)=>{fetch(f.url).then(response=>response.text()).then(data=>{let res={response:data};f.onload(res)}).catch(f.onerror())};
  363. }
  364. if(typeof GM_registerMenuCommand!='undefined'){
  365. _GM_registerMenuCommand=GM_registerMenuCommand;
  366. }else if(typeof GM!='undefined' && typeof GM.registerMenuCommand!='undefined'){
  367. _GM_registerMenuCommand=GM.registerMenuCommand;
  368. }else{
  369. _GM_registerMenuCommand=(s,f)=>{};
  370. }
  371. if(typeof GM_notification!='undefined'){
  372. _GM_notification=GM_notification;
  373. }else if(typeof GM!='undefined' && typeof GM.notification!='undefined'){
  374. _GM_notification=GM.notification;
  375. }else{
  376. _GM_notification=(s)=>{showTips(s)};
  377. }
  378. if(typeof GM_openInTab!='undefined'){
  379. _GM_openInTab=GM_openInTab;
  380. }else if(typeof GM!='undefined' && typeof GM.openInTab!='undefined'){
  381. _GM_openInTab=GM.openInTab;
  382. }else{
  383. _GM_openInTab=(s,t)=>{window.open(s)};
  384. }
  385. if(typeof GM_addStyle!='undefined'){
  386. _GM_addStyle=GM_addStyle;
  387. }else if(typeof GM!='undefined' && typeof GM.addStyle!='undefined'){
  388. _GM_addStyle=GM.addStyle;
  389. }else{
  390. _GM_addStyle=cssStr=>{
  391. let styleEle=document.createElement("style");
  392. styleEle.innerHTML=cssStr;
  393. document.head.appendChild(styleEle);
  394. };
  395. }
  396. var _unsafeWindow=(typeof unsafeWindow=='undefined')?window:unsafeWindow;//兼容 ios userscripts 的寫法
  397. var storage={
  398. supportGM: typeof GM_getValue=='function' && typeof GM_getValue('a','b')!='undefined',
  399. supportGMPromise: typeof GM!='undefined' && typeof GM.getValue=='function' && typeof GM.getValue('a','b')!='undefined',
  400. mxAppStorage:(function(){
  401. try{
  402. return window.external.mxGetRuntime().storage;
  403. }catch(e){
  404. }
  405. })(),
  406. operaUJSStorage:(function(){
  407. try{
  408. return window.opera.scriptStorage;
  409. }catch(e){
  410. }
  411. })(),
  412. setItem:function(key,value){
  413. if(this.operaUJSStorage){
  414. this.operaUJSStorage.setItem(key,value);
  415. }else if(this.mxAppStorage){
  416. this.mxAppStorage.setConfig(key,value);
  417. }else if(this.supportGM){
  418. GM_setValue(key,value);
  419. if(value==="" && typeof GM_deleteValue!='undefined'){
  420. GM_deleteValue(key);
  421. }
  422. }else if(this.supportGMPromise){
  423. GM.setValue(key,value);
  424. if(value==="" && typeof GM!='undefined' && typeof GM.deleteValue!='undefined'){
  425. GM.deleteValue(key);
  426. }
  427. }else if(window.localStorage){
  428. window.localStorage.setItem(key,value);
  429. }
  430. },
  431. getItem:function(key,cb){
  432. var value;
  433. if(this.operaUJSStorage){
  434. value=this.operaUJSStorage.getItem(key);
  435. }else if(this.mxAppStorage){
  436. value=this.mxAppStorage.getConfig(key);
  437. }else if(this.supportGM){
  438. value=GM_getValue(key);
  439. }else if(this.supportGMPromise){
  440. value=GM.getValue(key).then(v=>{cb(v)});
  441. return;
  442. }else if(window.localStorage){
  443. value=window.localStorage.getItem(key);
  444. };
  445. cb(value);
  446. }
  447. };
  448. var rulesData={},ruleUrls,updateDate,configPage="https://github.com/hoothin/UserScripts/tree/master/Pagetual";
  449. var ruleImportUrlReg=/greasyfork\.org\/.*scripts\/438684[^\/]*(\/discussions|\/?$)|github\.com\/hoothin\/UserScripts\/(tree\/master\/Pagetual|issues)/i;
  450. var allOfBody="body>*";
  451. _GM_registerMenuCommand(i18n("configure"), ()=>{
  452. _GM_openInTab(configPage,{active:true});
  453. });
  454. _GM_registerMenuCommand(i18n("editCurrent"), ()=>{
  455. let editTemp;
  456. if(ruleParser.curSiteRule.url && !ruleParser.curSiteRule.singleUrl){
  457. editTemp=ruleParser.curSiteRule;
  458. }else{
  459. editTemp={
  460. name: document.title,
  461. url: "^"+location.origin.replace(/\./g,"\\."),
  462. pageElement: ruleParser.curSiteRule.pageElement||""
  463. };
  464. }
  465. rulesData.editTemp=editTemp;
  466. storage.setItem("rulesData", rulesData);
  467. _GM_openInTab(configPage,{active:true});
  468. });
  469.  
  470. function getElementByXpath(xpath, contextNode, doc){
  471. doc = doc || document;
  472. contextNode = contextNode || doc;
  473. try {
  474. var result = doc.evaluate(xpath, contextNode, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
  475. return result.singleNodeValue && result.singleNodeValue.nodeType === 1 && result.singleNodeValue;
  476. } catch (err) {
  477. throw new Error(`Invalid xpath: ${xpath}`);
  478. }
  479. }
  480.  
  481. function getAllElementsByXpath(xpath, contextNode, doc){
  482. doc = doc || document;
  483. contextNode = contextNode || doc;
  484. var result = [];
  485. try {
  486. var query = doc.evaluate(xpath, contextNode, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  487. for (var i = 0; i < query.snapshotLength; i++) {
  488. var node = query.snapshotItem(i);
  489. if (node.nodeType === 1) result.push(node);
  490. }
  491. } catch (err) {
  492. throw new Error(`Invalid xpath: ${xpath}`);
  493. }
  494. return result;
  495. }
  496.  
  497. class RuleParser {
  498. constructor() {
  499. this.hpRules=[];
  500. this.customRules=[];
  501. this.rules=[];
  502. this.pageDoc=document;
  503. this.nextLinkHref=null;
  504. this.nextTitle="";
  505. this.oldUrl="";
  506. this.curUrl=location.href;
  507. this.curSiteRule={};
  508. }
  509.  
  510. initSavedRules(callback){
  511. var self=this;
  512. storage.getItem("hpRules", hpRules=>{
  513. if(hpRules)self.hpRules=hpRules;
  514. storage.getItem("customRules", customRules=>{
  515. if(customRules)self.customRules=customRules;
  516. storage.getItem("rules", rules=>{
  517. if(rules)self.rules=rules;
  518. callback();
  519. });
  520. });
  521. });
  522. }
  523.  
  524. saveCurSiteRule(){
  525. if(!this.curSiteRule || !this.curSiteRule.url || this.curSiteRule.singleUrl)return;
  526. this.hpRules=this.hpRules.filter(item=>{return item&&item.url!=this.curSiteRule.url});
  527. this.hpRules.unshift(this.curSiteRule);
  528. if(this.hpRules.length>30){
  529. this.hpRules.pop();
  530. }
  531. storage.setItem("hpRules", this.hpRules);
  532. }
  533.  
  534. requestJSON(url, callback){
  535. _GM_xmlhttpRequest({
  536. url: url,
  537. method: 'GET',
  538. timeout: 20000,
  539. onload: function(res) {
  540. let json=null;
  541. try{
  542. json=JSON.parse(res.response||res.responseText);
  543. }catch(e){
  544. debug(e);
  545. }
  546. callback(json);
  547. },
  548. onerror: function(e) {
  549. callback(null, e);
  550. },
  551. ontimeout: function(e) {
  552. callback(null, e);
  553. }
  554. });
  555. }
  556.  
  557. formatRule(item, type, from){
  558. switch(type){
  559. case 0:
  560. return {
  561. from:from,
  562. type:type,
  563. name:item.name,
  564. action:item.data.forceIframe=="true"?1:0,
  565. url:item.data.url,
  566. pageElement:item.data.pageElement,
  567. nextLink:item.data.nextLink,
  568. insert:item.data.insertBefore,
  569. insertPos:1,
  570. updatedAt:item.data.updated_at,
  571. css:item.data.Stylus+item.data.CSS,
  572. pageAction:item.data.bookmarklet
  573. };
  574. break;
  575. case 1:
  576. default:
  577. item.from=from;
  578. if(typeof(item.type) == "undefined")item.type=type;
  579. return item;
  580. break;
  581. }
  582. return null;
  583. }
  584.  
  585. addRuleByUrl(url, type, from, callback) {
  586. if(url.indexOf("?")==-1){
  587. url=url+"?"+Date.now();
  588. }else{
  589. url=url+"&"+Date.now();
  590. }
  591. this.requestJSON(url, (json,err)=>{
  592. if(!json){
  593. debug("Update "+url+" rules fail!");
  594. debug(err);
  595. }
  596. this.addRules(json, type, from);
  597. callback(json, err);
  598. });
  599. }
  600.  
  601. addRules(rules, type, from) {
  602. if(rules && rules.length>0){
  603. this.rules=this.rules.filter(item=>{return item.from!=from});
  604. rules.forEach(item=>{
  605. let rule=this.formatRule(item, type, from);
  606. if(rule){
  607. this.rules.unshift(rule);
  608. }
  609. });
  610. }
  611. }
  612.  
  613. getRule(callback) {
  614. if(noRuleTest){
  615. this.curSiteRule={};
  616. this.curSiteRule.url=location.origin+location.pathname;
  617. this.curSiteRule.singleUrl=true;
  618. callback();
  619. return;
  620. }
  621. if(this.curSiteRule && this.curSiteRule.url){
  622. return this.curSiteRule;
  623. }
  624. var self=this;
  625.  
  626. function setRule(r){
  627. self.curSiteRule=r;
  628. debug(r);
  629. callback();
  630. }
  631.  
  632. function ruleMatch(r){
  633. let pageElement,nextLink,insert;
  634. if(r.nextLink && r.nextLink!="0" && r.nextLink!=0){
  635. nextLink=r.type==0?getElementByXpath(r.nextLink):document.querySelector(r.nextLink);
  636. if(!nextLink)return false;
  637. }
  638. if(r.pageElement){
  639. pageElement=r.type==0?getElementByXpath(r.pageElement):document.querySelector(r.pageElement);
  640. if(!pageElement)return false;
  641. }
  642. if(r.insert){
  643. insert=r.type==0?getElementByXpath(r.insert):document.querySelector(r.insert);
  644. if(!insert)return false;
  645. }
  646. return true;
  647. }
  648.  
  649. function checkRule(r){
  650. let urlReg=new RegExp(r.url, "i");
  651. if(urlReg.test(location.href)){
  652. if(r.include){
  653. let include=r.type==0?getElementByXpath(r.include):document.querySelector(r.include);
  654. if(!include)return false;
  655. }
  656. if(r.wait){
  657. let waitTime=500,checkEval;
  658. if(isNaN(r.wait)){
  659. try{
  660. checkEval=Function("doc",'"use strict";' + r.wait);
  661. }catch(e){
  662. debug(e);
  663. }
  664. }else{
  665. waitTime=r.wait;
  666. }
  667. let checkReady=()=>{
  668. setTimeout(()=>{
  669. if(!ruleMatch(r) || (checkEval && !checkEval(document))){
  670. checkReady();
  671. }else{
  672. setRule(r);
  673. }
  674. },parseInt(waitTime));
  675. };
  676. checkReady();
  677. return true;
  678. }
  679. if(r.pinUrl){
  680. setRule(r);
  681. return true;
  682. }
  683. if(!ruleMatch(r)){
  684. return false;
  685. }
  686. setRule(r);
  687. return true;
  688. }
  689. return false;
  690. }
  691.  
  692. for(let i in this.hpRules){
  693. let rule=this.hpRules[i];
  694. if(!rule || !rule.url)continue;
  695. if(rule.singleUrl){
  696. if(location.origin+location.pathname==rule.url){
  697. setRule(rule);
  698. return;
  699. }
  700. continue;
  701. }
  702. if(checkRule(rule))return;
  703. }
  704. for(let i in this.customRules){
  705. let rule=this.customRules[i];
  706. if(!rule || !rule.url)continue;
  707. if(checkRule(rule))return;
  708. }
  709. let r=0;
  710. function searchByTime(){
  711. setTimeout(()=>{
  712. let end=r+50;
  713. end=end>self.rules.length?self.rules.length:end;
  714. for(;r<end;r++){
  715. let rule=self.rules[r];
  716. if(checkRule(rule))return;
  717. }
  718. if(end>=self.rules.length){
  719. self.curSiteRule={};
  720. self.curSiteRule.url=location.origin+location.pathname;
  721. self.curSiteRule.singleUrl=true;
  722. callback();
  723. return;
  724. }else{
  725. searchByTime();
  726. }
  727. },10);
  728. }
  729. searchByTime();
  730. }
  731.  
  732. geneSelector(ele){
  733. let selector=ele.tagName;
  734. //Google id class都是隨機。百度更過分,style script順序都是隨機的
  735. //if(ele.id) selector += '#' + ele.id;
  736. //if(ele.classList) selector += [].map.call(ele.classList,d=>'.'+d).join('');
  737. if(ele.tagName!="HTML" && ele.tagName!="BODY"){
  738. if(ele.className) selector += [].map.call(ele.classList,d=>'.'+d).join('');
  739. let parent = ele.parentElement;
  740. if(parent){
  741. selector = this.geneSelector(parent) + ' > ' + selector;
  742. if(!ele.className){
  743. let i,j=0;
  744. for(i=0;i<parent.children.length;i++){
  745. if(parent.children[i].tagName==ele.tagName){
  746. j++;
  747. if(parent.children[i]==ele){
  748. break;
  749. }
  750. }
  751. }
  752. selector += (parent.tagName=="HTML"?"":`:nth-of-type(${j})`);
  753. }
  754. }
  755. }
  756. return selector;
  757. }
  758.  
  759. getPageElement(doc, curWin, dontFind) {
  760. let pageElement=null;
  761. let self=this;
  762. let body=doc.body;
  763. if(this.curSiteRule.pageElement){
  764. pageElement=this.curSiteRule.type==0?getAllElementsByXpath(this.curSiteRule.pageElement,doc,doc):doc.querySelectorAll(this.curSiteRule.pageElement);
  765. }else if(!this.curSiteRule.singleUrl && this.curSiteRule.type==0){
  766. pageElement=[body];
  767. }
  768. if(this.curSiteRule.singleUrl && pageElement && pageElement.length>0 && pageElement[0].tagName=="TR"){
  769. let mainTr=this.insert.previousElementSibling,mainTdNum=0,newTdNum=0;
  770. [].forEach.call(mainTr.children, el=>{
  771. if(el.tagName=="TD" || el.tagName=="TH"){
  772. mainTdNum+=el.colSpan||1;
  773. }
  774. });
  775. [].forEach.call(pageElement[0].children, el=>{
  776. if(el.tagName=="TD" || el.tagName=="TH"){
  777. newTdNum+=el.colSpan||1;
  778. }
  779. });
  780. if(mainTdNum!=newTdNum){
  781. this.curSiteRule.pageElement=allOfBody;
  782. pageElement=[body];
  783. this.getInsert(true);
  784. }
  785. }
  786. if((this.curSiteRule.singleUrl || !this.curSiteRule.pageElement) && (!pageElement || pageElement.length==0) && curWin && !dontFind){
  787. if(!body)return null;
  788. let bodyHeight=parseInt(body.scrollHeight);
  789. let curHeight=bodyHeight;
  790. let windowHeight=window.innerHeight || document.documentElement.clientHeight;
  791. let needCheckNext=(doc==document && this.initNext);
  792. function checkElement(ele){
  793. if(ele.childNodes && ele.childNodes.length==1)ele=ele.childNodes[0];
  794. if(ele.tagName=="PICTURE"){
  795. self.curSiteRule.pageElement=self.geneSelector(ele.parentNode)+">"+ele.tagName;
  796. debug(self.curSiteRule.pageElement);
  797. return [ele];
  798. }
  799. if(curHeight/bodyHeight<=0.25){
  800. self.curSiteRule.pageElement=allOfBody;
  801. debug(self.curSiteRule.pageElement);
  802. return [body];
  803. }
  804. if(ele.tagName=="FORM"){
  805. self.curSiteRule.pageElement=self.geneSelector(ele)+">*";
  806. debug(self.curSiteRule.pageElement);
  807. return ele.children;
  808. }
  809. if(ele.children.length==0 && !self.curSiteRule.pageElement){
  810. if(ele.parentNode.tagName=="P")ele=ele.parentNode;
  811. self.curSiteRule.pageElement=self.geneSelector(ele.parentNode)+">"+ele.tagName;
  812. debug(self.curSiteRule.pageElement);
  813. return [ele];
  814. }
  815. let i,maxHeight=curHeight*0.55,curMaxEle=null,curMaxArea=0,maxWidth=0;
  816. let isHori=true;
  817. let offsetTop=ele.children[0].offsetTop;
  818. for(i=1;i<ele.children.length;i++){
  819. if(ele.children[i].offsetTop!=offsetTop){
  820. isHori=false;
  821. break;
  822. }
  823. }
  824. for(i=0;i<ele.children.length;i++){
  825. let curNode=ele.children[i];
  826. if(curNode.tagName=="CANVAS")continue;
  827. if(curNode.tagName!="IMG" && /^\s*$/.test(curNode.innerText))continue;
  828. if(needCheckNext && !curNode.contains(self.initNext) && getElementTop(curNode)>windowHeight){
  829. continue;
  830. }
  831. let comStyle=curWin.getComputedStyle(curNode);
  832. let h=parseInt(curNode.scrollHeight);
  833. let w=parseInt(curNode.scrollWidth);
  834. if(isNaN(h) || isNaN(w))continue;
  835. if(isHori && h==0)continue;
  836. let a=h*w+h,moreChild=curNode.children[0];
  837. while(moreChild){
  838. comStyle=curWin.getComputedStyle(moreChild);
  839. let ch=parseInt(moreChild.scrollHeight);
  840. let cw=parseInt(moreChild.scrollWidth);
  841. if(h<ch)h=ch;
  842. if(moreChild.innerText!="" && !isNaN(ch) && !isNaN(cw)){
  843. a+=ch*cw;
  844. }
  845. moreChild=moreChild.nextElementSibling;
  846. }
  847. let isMax=false;
  848. if(isHori){
  849. if(maxWidth<w){
  850. isMax=true;
  851. }else if(maxWidth==w && curMaxArea<a){
  852. isMax=true;
  853. }
  854. }else{
  855. isMax=curMaxArea<a;
  856. }
  857. if(curMaxEle==null || isMax){
  858. if(h>0 || !isHori)curHeight=h;
  859. curMaxArea=a;
  860. maxWidth=w;
  861. curMaxEle=curNode;
  862. }
  863. }
  864. if(curMaxEle && (isHori || curHeight>maxHeight || (needCheckNext && curHeight>windowHeight && ele.contains(self.initNext)))){
  865. return checkElement(curMaxEle);
  866. }
  867. if(ele.tagName=="P" || ele.tagName=="BR")ele=ele.parentNode;
  868. if(ele.tagName=="TBODY"){
  869. self.curSiteRule.pageElement=self.geneSelector(ele)+">*";
  870. if(ele.children.length>0 && ele.children[0].querySelector("th")){
  871. self.curSiteRule.pageElement+=":not(:first-child)";
  872. }
  873. debug(self.curSiteRule.pageElement);
  874. return ele.children;
  875. }
  876. self.curSiteRule.pageElement=self.geneSelector(ele);
  877. if(ele.children.length>1){
  878. let middleChild=ele.children[parseInt(ele.children.length/2)];
  879. if((middleChild.style && middleChild.style.position=="absolute" && middleChild.style.left && middleChild.style.top) || ele.tagName=="UL" || curHeight==0){
  880. ele=[ele];
  881. }else{
  882. self.curSiteRule.pageElement+=">*";
  883. ele=ele.children;
  884. }
  885. }else{
  886. ele=[ele];
  887. }
  888. debug(self.curSiteRule.pageElement);
  889. return ele;
  890. }
  891. pageElement=checkElement(body);
  892. if(pageElement)this.saveCurSiteRule();
  893. }
  894. return pageElement;
  895. }
  896.  
  897. getPage(doc){
  898. if(_unsafeWindow.Discourse)return {};
  899. let canSave=false;//發現頁碼選擇器在其他頁對不上,還是別保存了
  900. let url=this.curUrl.replace("#!","").replace("index.php?","?");
  901. let pageNum=1,preStr="",afterStr="";
  902. let pageMatch1=url.match(/(.*[a-z\/\-_](?:p|page)?\/?)(\d+)(\.s?html?$|\/?$)/i);
  903. let pageMatch2=url.match(/(.*[\?&]p(?:age)?=)(\d+)($|[#&].*)/i);
  904. if(pageMatch1){
  905. preStr=pageMatch1[1];
  906. pageNum=parseInt(pageMatch1[2]);
  907. afterStr=pageMatch1[3];
  908. }else if(pageMatch2){
  909. preStr=pageMatch2[1];
  910. pageNum=parseInt(pageMatch2[2]);
  911. afterStr=pageMatch2[3];
  912. }
  913. let curPage=doc,i,cur,jsNext;
  914. let next1,next2,next3,next4,nextJs1,nextJs2,nextJs3;
  915. let next=curPage.querySelector(".page-next>a")||
  916. curPage.querySelector("a.next_page")||
  917. curPage.querySelector("#next_page")||
  918. curPage.querySelector(".nextPage")||
  919. curPage.querySelector("a[data-pagination=next]")||
  920. curPage.querySelector("ul.pagination>li.active+li>a")||
  921. curPage.querySelector(".pagination a[rel=next]")||
  922. curPage.querySelector(".pagination-nav__item--next>a")||
  923. curPage.querySelector("a[title='Next page']")||
  924. curPage.querySelector("a.pageright")||
  925. curPage.querySelector("a#rightFix")||
  926. curPage.querySelector("a#next")||
  927. curPage.querySelector(".next>a")||
  928. curPage.querySelector(".next>button")||
  929. curPage.querySelector("a[alt=next]")||
  930. curPage.querySelector("button.next")||
  931. curPage.querySelector("[title=next]")||
  932. getElementByXpath("//a[contains(@class, 'page__next')]",curPage,curPage);
  933. if(!next){
  934. let nexts=curPage.querySelectorAll("a.next");
  935. for(i=0;i<nexts.length;i++){
  936. if(!/^([上前首尾][一1]?[页頁张張]|previous(\s*page)?\s*›?$|前のページ)/i.test(nexts[i].innerText.trim()) &&
  937. nexts[i].style.display!=="none" &&
  938. nexts[i].parentNode.style.display!=="none"){
  939. next=nexts[i];
  940. break;
  941. }
  942. }
  943. }
  944. if(next && (!next.href || /^javascript:/.test(next.href) || next.getAttribute("href")=="#")){
  945. jsNext=next;
  946. next=null;
  947. }
  948. if(!next){
  949. next=curPage.querySelectorAll("[aria-label='Next page']");
  950. if(next && next.length==1){
  951. next=next[0];
  952. if(!next.href || /^javascript:/.test(next.href) || next.getAttribute("href")=="#"){
  953. if(!jsNext)jsNext=next;
  954. next=null;
  955. }
  956. }else{
  957. next=null;
  958. }
  959. }
  960. if(!next){
  961. next=curPage.querySelectorAll("[aria-label='Next']");
  962. if(next && next.length==1){
  963. next=next[0];
  964. if(!next.href || /^javascript:/.test(next.href) || next.getAttribute("href")=="#"){
  965. if(!jsNext)jsNext=next;
  966. next=null;
  967. }
  968. }else{
  969. next=null;
  970. }
  971. }
  972. if(next && /^[下后後][一1]?[章话話篇]/i.test(next.innerText.trim())){
  973. next2=next;
  974. next=null;
  975. }
  976. if(!next){
  977. next=curPage.querySelector("a.curr");
  978. if(next){
  979. next=next.nextSibling;
  980. }
  981. }
  982. if(!next){
  983. next=curPage.querySelector("div.wp-pagenavi>span.current+a,div.page-nav>span.current+a,div.article-paging>span+a");
  984. }
  985. if(!next){
  986. let pageDiv=curPage.querySelector("div.pages>ul");
  987. if(pageDiv){
  988. cur=pageDiv.querySelector("li>b");
  989. if(cur)next=cur.parentNode.nextElementSibling;
  990. if(next)next=next.querySelector("a");
  991. }
  992. }
  993. if(!next){
  994. cur=curPage.querySelector(".number>ul>li.active");
  995. if(cur)next=cur.nextElementSibling;
  996. if(next)next=next.querySelector("a");
  997. }
  998. if(!next){
  999. let aTags=curPage.querySelectorAll("a,button");
  1000. for(i=aTags.length-1;i>=0;i--){
  1001. if(next1 && next2 && next3 && next4)break;
  1002. let aTag=aTags[i];
  1003. if(aTag.innerText=="§")continue;
  1004. if(aTag.innerText.length>50)continue;
  1005. if(aTag.style.display=="none")continue;
  1006. if(aTag.href && /next$/i.test(aTag.href))continue;
  1007. if(aTag.className && /slick|slide/i.test(aTag.className))continue;
  1008. if(!next1){
  1009. if(aTag.innerText.length>15)continue;
  1010. if(/^[下后後][一1]?[页頁张張]|^next([ _-]?page)?\s*[›>→»]?$|次のページ|^次へ?$/i.test(aTag.innerText.trim())){
  1011. if(!aTag.href || /^javascript:/.test(aTag.href) || aTag.getAttribute("href")=="#"){
  1012. if(!nextJs1)nextJs1=aTag;
  1013. }else{
  1014. next1=aTag;
  1015. }
  1016. }
  1017. }
  1018. if(!next2){
  1019. if(aTag.innerText.length>15)continue;
  1020. if(/^[下后後][一1]?[章话話篇]/i.test(aTag.innerText.trim()) || /nextpage/i.test(aTag.className)){
  1021. if(!aTag.href || /^javascript:/.test(aTag.href) || aTag.getAttribute("href")=="#"){
  1022. if(!nextJs2)nextJs2=aTag;
  1023. }else{
  1024. next2=aTag;
  1025. }
  1026. }
  1027. }
  1028. if(!next3){
  1029. if(aTag.innerText.length>15)continue;
  1030. if(aTag.innerText=="&gt;" || aTag.innerText=="▶" || aTag.innerText==">" || aTag.innerText=="›" || aTag.innerText=="→" || aTag.innerText=="»"){
  1031. if(!aTag.href || /^javascript:/.test(aTag.href) || aTag.getAttribute("href")=="#"){
  1032. if(!nextJs3)nextJs3=aTag;
  1033. }else{
  1034. next3=aTag;
  1035. }
  1036. }
  1037. }
  1038. if(!aTag.href || /^javascript:/.test(aTag.href) || aTag.getAttribute("href")=="#")continue;
  1039. if(!next4 && aTag.href.length<250){
  1040. let _aHref=aTag.href.replace("?&","?").replace("#!","").replace("index.php?","?");
  1041. let _aHrefTrim=_aHref;
  1042. if(preStr)_aHrefTrim=_aHrefTrim.replace(preStr,"");
  1043. if(afterStr)_aHrefTrim=_aHrefTrim.replace(afterStr,"");
  1044. if(pageNum<999 && _aHrefTrim==pageNum+1){
  1045. next4=aTag;
  1046. }else if(this.curUrl!=aTag.href){
  1047. let _url=url.replace(/\.s?html?$/i,"");
  1048. _aHref=_aHref.replace(/\.s?html?$/i,"");
  1049. if(_aHref.indexOf(_url)!=-1 && /^[\/\?&]?[_-]?(p|page)?=?\/?2(\/|\?|&|$)/i.test(_aHref.replace(_url,""))){
  1050. let curHref=aTag.getAttribute("href");
  1051. let pageOne=curHref.replace(/\/2(\/|\?|&|$)/,"/1$1");
  1052. if(pageOne==curHref)pageOne=null;
  1053. else pageOne=curPage.querySelector(`a[href='${pageOne}']`);
  1054. if(!pageOne || pageOne.className!=curHref.className)next4=aTag;
  1055. }
  1056. }
  1057. }
  1058. }
  1059. if(next3){
  1060. let eles=getAllElementsByXpath(`//a[text()='${next3.innerText}']`,curPage,curPage);
  1061. if(eles.length>1)next3=null;
  1062. }
  1063. }
  1064. if(!next)next=next1||next4||next3||next2||jsNext||nextJs1||nextJs3||nextJs2;
  1065. if(next && next.classList.contains("results-more"))next=null;
  1066. return {next:next,canSave:canSave};
  1067. }
  1068.  
  1069. canonicalUri(src) {
  1070. if(src.charAt(0)=="#")return location.href+src;
  1071. var root_page = /^[^?#]*\//.exec(location.href)[0],
  1072. base_path = location.pathname.replace(/\/[^\/]+\.[^\/]+$/, "/"),
  1073. root_domain = /^\w+\:\/\/\/?[^\/]+/.exec(root_page)[0],
  1074. absolute_regex = /^\w+\:\/\//;
  1075. src=src.replace(/\.\//,"");
  1076. if (/^\/\/\/?/.test(src)){
  1077. src = location.protocol + src;
  1078. }
  1079. else if (!absolute_regex.test(src) && src.charAt(0) != "/"){
  1080. src = (base_path || "") + src;
  1081. }
  1082. return (absolute_regex.test(src) ? src : ((src.charAt(0) == "/" ? root_domain : root_page) + src));
  1083. }
  1084.  
  1085. getLinkByPage(url, pageNum) {
  1086. if(!url)return;
  1087. if(this.curSiteRule.pageNum){
  1088. let result=this.curSiteRule.pageNum;
  1089. let strMatch=result.match(/\{.*?}/);
  1090. if(!strMatch)return null;
  1091. let urlReg=new RegExp("("+result.replace(strMatch[0], ")\\d+(")+")","i");
  1092. let code=strMatch[0].replace(/^{/,"").replace(/}$/,"").replace(/\$p/g,pageNum);
  1093. if(code==pageNum){
  1094. result=url.replace(urlReg,"$1"+code+"$2");
  1095. }else{
  1096. try{
  1097. code=Function('"use strict";return ' + code)();
  1098. result=url.replace(urlReg,"$1"+code+"$2");
  1099. }catch(e){
  1100. debug(e);
  1101. }
  1102. }
  1103. return result==url?url.replace(/([&\/\?](p=|page[=\/_-]?))\d+/i, "$1"+pageNum).replace(/([_-])\d+\./i, "$1"+pageNum+"."):result;
  1104. }else{
  1105. return url.replace(/([&\/\?](p=|page[=\/_-]?))\d+/i, "$1"+pageNum).replace(/([_-])\d+\./i, "$1"+pageNum+".");
  1106. }
  1107. }
  1108.  
  1109. getNextLink(doc) {
  1110. let nextLink=null,page,href;
  1111. let getNextLinkByForm=(form,n)=>{
  1112. let params=[];
  1113. [].forEach.call(form.querySelectorAll("input"), input=>{
  1114. if(n && /^(p|page)$/i.test(input.name)){
  1115. params.push('p='+n);
  1116. }else{
  1117. params.push(input.name+'='+input.value);
  1118. }
  1119. });
  1120. return form.action+'?'+params.join('&');
  1121. };
  1122. if(this.curSiteRule.pageElementByJs){
  1123. this.nextLinkHref="#";
  1124. return true;
  1125. }else if(this.curSiteRule.nextLinkByJs){
  1126. try{
  1127. let targetUrl=Function("doc",'"use strict";' + this.curSiteRule.nextLinkByJs)(doc);
  1128. if(targetUrl)nextLink={href:targetUrl};
  1129. }catch(e){
  1130. debug(e);
  1131. }
  1132. }else if(this.curSiteRule.nextLinkByUrl){
  1133. let targetUrl=this.curUrl.replace(new RegExp(this.curSiteRule.nextLinkByUrl[0],"i"), this.curSiteRule.nextLinkByUrl[1]);
  1134. if(targetUrl != this.curUrl){
  1135. let reps=targetUrl.match(/{.*?}/g);
  1136. if(reps){
  1137. reps.forEach(rep=>{
  1138. let code=rep.replace("{","").replace("}","");
  1139. let result=code.match(/^(\d+)\+1$/);
  1140. if(result){
  1141. result=parseInt(result[1])+1;
  1142. }else{
  1143. try{
  1144. result=Function('"use strict";return ' + code)();
  1145. }catch(e){
  1146. debug(e);
  1147. }
  1148. }
  1149. targetUrl=targetUrl.replace(rep, result);
  1150. });
  1151. }
  1152. }
  1153. nextLink={href:targetUrl};
  1154. }else if(this.curSiteRule.nextLink){
  1155. if(this.curSiteRule.nextLink!="0" && this.curSiteRule.nextLink!=0){
  1156. nextLink=this.curSiteRule.type==0?getElementByXpath(this.curSiteRule.nextLink,doc,doc):doc.querySelector(this.curSiteRule.nextLink);
  1157. }
  1158. }else{
  1159. page=this.getPage(doc);
  1160. nextLink=page.next;
  1161. if(nextLink){
  1162. if(nextLink.tagName=="INPUT" && nextLink.parentNode.tagName=="FORM"){
  1163. let form=nextLink.parentNode;
  1164. nextLink.href=getNextLinkByForm(form);
  1165. }
  1166. if(nextLink.parentNode.style.display=="none" || nextLink.style.display=="none" || nextLink.classList.contains("noClick") || nextLink.hasAttribute("disabled")){
  1167. this.nextLinkHref=false;
  1168. return null;
  1169. }else if(doc==document){
  1170. if((!nextLink.href || /^javascript:/.test(nextLink.href)) && !isVisible(nextLink, _unsafeWindow)){
  1171. this.nextLinkHref=false;
  1172. return null;
  1173. }else{
  1174. let nextLinkCs=_unsafeWindow.getComputedStyle(nextLink);
  1175. if(nextLinkCs.cursor=="not-allowed"){
  1176. this.nextLinkHref=false;
  1177. return null;
  1178. }
  1179. this.initNext=nextLink;
  1180. }
  1181. }
  1182. let form=doc.querySelector('#search-form');
  1183. if(!nextLink.href && nextLink.hasAttribute("onclick") && form){
  1184. if(form && /^\d+$/.test(nextLink.innerText)){
  1185. href=getNextLinkByForm(form, nextLink.innerText);
  1186. }
  1187. }
  1188. }
  1189. }
  1190. if(nextLink){
  1191. let needUrl=(this.curSiteRule.action==0 || this.curSiteRule.action==1);
  1192. if(!href)href=nextLink.href;
  1193. if(href && nextLink.getAttribute){
  1194. let _href=nextLink.getAttribute("href");
  1195. if(!_href || _href.charAt(0)=="#"){
  1196. href=_href;
  1197. }
  1198. }
  1199.  
  1200. if((href===""||href===null) && needUrl){
  1201. this.nextLinkHref=false;
  1202. }else if(/^(javascript:void\(0\)|#)/.test(href) && needUrl){
  1203. this.nextLinkHref=false;
  1204. }else{
  1205. this.nextLinkHref=(href && !/^(javascript:|#)/.test(href))?this.canonicalUri(href):"#";
  1206. if(this.nextLinkHref!="#" && (this.nextLinkHref==this.curUrl || this.nextLinkHref==this.curUrl+"#" || this.nextLinkHref==this.oldUrl || this.nextLinkHref==this.oldUrl+"#")){
  1207. this.nextLinkHref=false;
  1208. }else if(doc==document)debug(nextLink);
  1209. }
  1210. }else{
  1211. this.nextLinkHref=false;
  1212. }
  1213. this.preload();
  1214. return nextLink;
  1215. }
  1216.  
  1217. preload(){
  1218. if(!rulesData.preload)return;
  1219. if(!this.nextLinkHref || this.nextLinkHref=="#")return;
  1220. let self=this;
  1221. if(this.curSiteRule && this.curSiteRule.action==1){
  1222. if(!this.preloadIframe){
  1223. this.preloadIframe = document.createElement('iframe');
  1224. let iframe = this.preloadIframe;
  1225. iframe.name = 'pagetual-iframe';
  1226. iframe.width = '100%';
  1227. iframe.height = '0';
  1228. iframe.frameBorder = '0';
  1229. if(ruleParser.curSiteRule.sandbox!=false){
  1230. iframe.sandbox="allow-same-origin allow-scripts allow-popups allow-forms";
  1231. }
  1232. iframe.style.cssText = 'margin:0!important;padding:0!important;visibility:hidden!important;';
  1233. iframe.addEventListener('load', function (e) {
  1234. try{
  1235. let doc=iframe.contentDocument || iframe.contentWindow.document;
  1236. var body = doc.body;
  1237. if (body && body.firstChild) {
  1238. self.lazyImgAction(body.children);
  1239. }
  1240. }catch(e){
  1241. return;
  1242. }
  1243. }, false);
  1244. document.body.appendChild(iframe);
  1245. }
  1246. this.preloadIframe.src = this.nextLinkHref;
  1247. }else{
  1248. _GM_xmlhttpRequest({
  1249. url: this.nextLinkHref,
  1250. method: 'GET',
  1251. overrideMimeType: 'text/html;charset='+document.charset,
  1252. headers: {
  1253. 'Referer': location.href
  1254. },
  1255. timeout: 5000,
  1256. onload: function(res) {
  1257. var doc=null;
  1258. try {
  1259. doc=document.implementation.createHTMLDocument('');
  1260. doc.documentElement.innerHTML=res.response;
  1261. var body = doc.body;
  1262. if (body && body.firstChild) {
  1263. self.lazyImgAction(body.children);
  1264. }
  1265. if(!self.preloadDiv){
  1266. self.preloadDiv = document.createElement('div');
  1267. self.preloadDiv.id = "pagetual-preload";
  1268. self.preloadDiv.style.cssText = 'display:none!important;';
  1269. document.body.appendChild(self.preloadDiv);
  1270. self.checkedImgs={};
  1271. }
  1272. [].forEach.call(doc.images, i=>{
  1273. let iSrc=i.src;
  1274. if(iSrc && !self.checkedImgs[iSrc]){
  1275. self.checkedImgs[iSrc] = true;
  1276. let img = document.createElement('img');
  1277. img.src = iSrc;
  1278. self.preloadDiv.appendChild(img);
  1279. }
  1280. });
  1281. }
  1282. catch (e) {
  1283. return;
  1284. }
  1285. }
  1286. });
  1287. }
  1288. }
  1289.  
  1290. getInsert(refresh) {
  1291. if(refresh){
  1292. this.insert=null;
  1293. }
  1294. if(this.insert && !refresh){
  1295. let parent=this.insert;
  1296. while(parent && parent.nodeName!="BODY"){
  1297. parent=parent.parentNode;
  1298. }
  1299. if(parent && parent.nodeName=="BODY"){
  1300. return this.insert;
  1301. }
  1302. }
  1303. if(this.curSiteRule.insert){
  1304. this.insert=this.curSiteRule.type==0?getElementByXpath(this.curSiteRule.insert,document):document.querySelector(this.curSiteRule.insert);
  1305. }else{
  1306. let pageElement=this.getPageElement(document, _unsafeWindow);
  1307. if(pageElement && pageElement.length>0){
  1308. var pELast = pageElement[pageElement.length - 1];
  1309. this.insert = pELast.nextSibling ? pELast.nextSibling : pELast.parentNode.appendChild(document.createTextNode(' '));
  1310. }
  1311. }
  1312. return this.insert;
  1313. }
  1314.  
  1315. pageInit(doc,eles){
  1316. let code=this.curSiteRule.pageInit;
  1317. if(code){
  1318. try{
  1319. Function("doc","eles",'"use strict";' + code)(doc,eles);
  1320. }catch(e){
  1321. debug(e);
  1322. }
  1323. }
  1324. }
  1325.  
  1326. pageAction(doc,eles){
  1327. let code=this.curSiteRule.pageAction;
  1328. if(code){
  1329. try{
  1330. Function("doc","eles",'"use strict";' + code)(doc,eles);
  1331. }catch(e){
  1332. debug(e);
  1333. }
  1334. }
  1335. this.lazyImgAction(eles);
  1336. this.openInNewTab(eles);
  1337. }
  1338.  
  1339. openInNewTab(eles){
  1340. if(rulesData.openInNewTab){
  1341. [].forEach.call(eles, ele=>{
  1342. if(ele.tagName=="A" && ele.href && !/^(mailto:|javascript:|#)/.test(ele.href)){
  1343. ele.setAttribute('target', '_blank');
  1344. }else{
  1345. [].forEach.call(ele.querySelectorAll('a[href]:not([href^="mailto:"]):not([href^="javascript:"]):not([href^="#"])'), a=>{
  1346. a.setAttribute('target', '_blank');
  1347. if (a.getAttribute('onclick') == 'atarget(this)') {
  1348. a.removeAttribute('onclick');
  1349. }
  1350. });
  1351. }
  1352. });
  1353. }
  1354. }
  1355.  
  1356. lazyImgAction(eles){
  1357. let setLazyImg=img=>{
  1358. let realSrc;
  1359. if(img.getAttribute("_src") && !img.src){
  1360. realSrc=img.getAttribute("_src");
  1361. }else if(img.dataset && img.dataset.original){
  1362. realSrc=img.dataset.original;
  1363. }else if(img.dataset && img.dataset.src){
  1364. realSrc=img.dataset.src;
  1365. }else if(img._lazyrias && img._lazyrias.srcset){
  1366. realSrc=img._lazyrias.srcset[img._lazyrias.srcset.length-1];
  1367. }else if(img.dataset && img.dataset.origFile){
  1368. realSrc=img.dataset.origFile;
  1369. }else if(img.srcset){
  1370. var srcs=img.srcset.split(/[xw],/),largeSize=0;
  1371. srcs.forEach(srci=>{
  1372. let srcInfo=srci.trim().split(" "),curSize=parseInt(srcInfo[1]);
  1373. if(srcInfo[1] && curSize>largeSize){
  1374. largeSize=curSize;
  1375. realSrc=srcInfo[0];
  1376. }
  1377. });
  1378. }
  1379. if(realSrc){
  1380. img.src=realSrc;
  1381. img.style.display="block";
  1382. }
  1383. };
  1384. [].forEach.call(eles, ele=>{
  1385. if(ele.tagName=="IMG"){
  1386. setLazyImg(ele);
  1387. }else{
  1388. [].forEach.call(ele.querySelectorAll("img"), img=>{
  1389. setLazyImg(img);
  1390. });
  1391. }
  1392. if(ele.tagName=="A" && ele.classList.contains("lazyload")){
  1393. if(ele.dataset.original){
  1394. ele.style.backgroundImage='url("'+ele.dataset.original+'")';
  1395. }
  1396. }else{
  1397. [].forEach.call(ele.querySelectorAll("a.lazyload"), a=>{
  1398. if(a.dataset.original){
  1399. a.style.backgroundImage='url("'+a.dataset.original+'")';
  1400. }
  1401. });
  1402. }
  1403. });
  1404. let lazyImgSrc=this.curSiteRule.lazyImgSrc;
  1405. if(lazyImgSrc){
  1406. [].forEach.call(eles, ele=>{
  1407. [].forEach.call(ele.querySelectorAll("img"), img=>{
  1408. if(img.getAttribute(lazyImgSrc)){
  1409. img.src=img.getAttribute(lazyImgSrc);
  1410. }
  1411. });
  1412. });
  1413. }
  1414. }
  1415.  
  1416. initPage(callback){
  1417. let self=this;
  1418. curPage=1;
  1419. //if(this.curSiteRule.url && !this.curSiteRule.singleUrl)return;
  1420. this.curSiteRule={};
  1421. this.pageDoc=document;
  1422. this.nextLinkHref=null;
  1423. this.curUrl=location.href;
  1424. this.getRule(()=>{
  1425. if(self.curSiteRule.enable==0){
  1426. debug("Stop as rule disable");
  1427. isPause=true;
  1428. return;
  1429. }
  1430. if(self.curSiteRule && !self.curSiteRule.singleUrl){
  1431. self.hpRules=self.hpRules.filter(item=>{return item&&item.url!=self.curSiteRule.url});
  1432. self.hpRules.unshift(self.curSiteRule);
  1433. if(self.hpRules.length>30){
  1434. self.hpRules.pop();
  1435. }
  1436. storage.setItem("hpRules", self.hpRules);
  1437. }
  1438. let css=self.curSiteRule.css;
  1439. if(css){
  1440. _GM_addStyle(css);
  1441. }
  1442. let autoClick=self.curSiteRule.autoClick;
  1443. if(autoClick){
  1444. let autoClickBtn;
  1445. try{
  1446. autoClickBtn=document.querySelector(autoClick);
  1447. }catch(e){
  1448. autoClickBtn=getElementByXpath(autoClick);
  1449. }
  1450. if(autoClickBtn){
  1451. emuClick(autoClickBtn);
  1452. }
  1453. }
  1454. let code=self.curSiteRule.init;
  1455. if(code){
  1456. try{
  1457. Function('doc','win','iframe','"use strict";' + code)(null,null,null);
  1458. }catch(e){
  1459. debug(e);
  1460. }
  1461. }
  1462. self.getNextLink(document);
  1463. callback();
  1464. });
  1465. }
  1466.  
  1467. insertPage(doc, eles, url, callback, tried){
  1468. this.oldUrl=this.curUrl;
  1469. let oldTitle=this.pageDoc.title;
  1470. this.pageDoc=doc;
  1471. this.curUrl=url;
  1472. let nextLink=this.getNextLink(doc);
  1473. this.nextTitle="";
  1474. if(this.curSiteRule.pageBarText){
  1475. if(this.curSiteRule.pageBarText==1){
  1476. this.nextTitle=doc.title;
  1477. }else{
  1478. try{
  1479. this.nextTitle=Function("doc",'"use strict";' + this.curSiteRule.pageBarText)(doc);
  1480. }catch(e){
  1481. debug(e);
  1482. }
  1483. }
  1484. }
  1485. if(curPage==1 && !tried && !nextLink && this.curSiteRule.singleUrl && this.curSiteRule.pageElement && this.curSiteRule.action!=0){
  1486. this.curSiteRule.action=1;
  1487. this.curUrl=location.href;
  1488. return false;
  1489. }
  1490. if(callback)callback(eles);
  1491. this.getInsert();
  1492. var self=this,newEles=[];
  1493. if(!eles || eles.length==0 || !self.insert || !self.insert.parentNode){
  1494. }else{
  1495. this.pageInit(doc, eles);
  1496. [].forEach.call(eles, ele=>{
  1497. let newEle=ele.cloneNode(true);
  1498. let oldCanvass=ele.querySelectorAll("canvas");
  1499. let newCanvass=newEle.querySelectorAll("canvas");
  1500. for(let i=0;i<oldCanvass.length;i++){
  1501. let oldCanvas=oldCanvass[i];
  1502. let newCanvas=newCanvass[i];
  1503. newCanvas.getContext('2d').drawImage(oldCanvas, 0, 0);
  1504. }
  1505. if(self.curSiteRule.insertPos==2){
  1506. self.insert.appendChild(newEle);
  1507. }else{
  1508. self.insert.parentNode.insertBefore(newEle, self.insert);
  1509. }
  1510. newEles.push(newEle);
  1511. });
  1512. }
  1513. this.pageAction(doc, newEles);
  1514. if(this.oldUrl!=location.href){
  1515. let isJs=/^(javascript|#)/.test(this.oldUrl.replace(location.href,""));
  1516. if(rulesData.enableHistory && !isJs){
  1517. _unsafeWindow.history.replaceState(undefined, oldTitle, this.oldUrl);
  1518. document.title=oldTitle;
  1519. }
  1520. }
  1521. return true;
  1522. }
  1523. }
  1524. var ruleParser = new RuleParser();
  1525.  
  1526. function initConfig(){
  1527. initView();
  1528. _GM_registerMenuCommand(i18n(forceState==1?"enable":"disableSite"), ()=>{
  1529. storage.setItem("forceState_"+location.host, (forceState==1?0:1));
  1530. location.reload();
  1531. });
  1532. _GM_registerMenuCommand(i18n("update"), ()=>{
  1533. updateRules(()=>{
  1534. showTips(i18n("updateSucc"));
  1535. location.reload();
  1536. },(rule,err)=>{
  1537. showTips("Update "+rule.url+" rules fail!");
  1538. });
  1539. showTips(i18n("beginUpdate"));
  1540. });
  1541.  
  1542. var configCon,insertPos;
  1543. if(ruleImportUrlReg.test(location.href)){
  1544. document.addEventListener("click", e=>{
  1545. if(e.target.tagName=="PRE"){
  1546. let nameAttr=e.target.getAttribute("name");
  1547. if(nameAttr=="pagetual" || nameAttr=="user-content-pagetual" || location.href.indexOf("greasyfork.org") != -1){
  1548. let rules=e.target.innerText.trim();
  1549. let isContent=/['"]name['"]/i.test(rules);
  1550. if(isContent){
  1551. let ruleList=JSON.parse(`[${rules}]`);
  1552. for(let i in ruleList){
  1553. let hasRule = false;
  1554. let r = ruleList[i];
  1555. for(let j in ruleParser.customRules){
  1556. if(ruleParser.customRules[j].name == r.name){
  1557. ruleParser.customRules[j] = r;
  1558. hasRule = true;
  1559. break;
  1560. }
  1561. }
  1562. if(!hasRule)ruleParser.customRules.push(r);
  1563. }
  1564. storage.setItem("customRules", ruleParser.customRules);
  1565. showTips(i18n("importSucc"));
  1566. }else{
  1567. rules=rules.split("\n");
  1568. let diff=false;
  1569. for(let c=0;c<rules.length;c++){
  1570. let urlArr=rules[c].split("|"),url,type=1;
  1571. if(urlArr.length==1){
  1572. url=urlArr[0].trim();
  1573. if(!/^http/.test(url)){
  1574. showTips("Wrong url, check again!");
  1575. return;
  1576. }
  1577. }else if(urlArr.length==2){
  1578. type=urlArr[0].trim();
  1579. url=urlArr[1].trim();
  1580. if(!/^http/.test(url)){
  1581. showTips("Wrong url, check again!");
  1582. return;
  1583. }
  1584. }else{
  1585. break;
  1586. }
  1587. let maxId=0,hasUrl=false;
  1588. if(!rulesData.urls){
  1589. rulesData.urls=[];
  1590. maxId=1;
  1591. }else{
  1592. rulesData.urls.forEach(u=>{
  1593. if(maxId<u.id){
  1594. maxId=u.id;
  1595. }
  1596. if(u.url==url){
  1597. hasUrl=true;
  1598. }
  1599. });
  1600. if(hasUrl)break;
  1601. }
  1602. diff=true;
  1603. if(!rulesData.sort)rulesData.sort=[1];
  1604. rulesData.urls.push({id:maxId+1,url:url,type:type});
  1605. rulesData.sort.unshift(maxId+1);
  1606. }
  1607. if(!diff)return;
  1608. storage.setItem("rulesData", rulesData);
  1609.  
  1610. if(rulesData.urls)ruleUrls=ruleUrls.concat(rulesData.urls);
  1611. if(rulesData.sort){
  1612. let urls=[];
  1613. rulesData.sort.forEach(id=>{
  1614. for(let s=0;s<ruleUrls.length;s++){
  1615. if(id==ruleUrls[s].id){
  1616. urls.push(ruleUrls[s]);
  1617. break;
  1618. }
  1619. }
  1620. });
  1621. ruleUrls=urls;
  1622. }
  1623. updateRules(()=>{
  1624. showTips(i18n("updateSucc"));
  1625. },(rule,err)=>{
  1626. showTips("Update "+rule.url+" rules fail!");
  1627. });
  1628. showTips(i18n("beginUpdate"));
  1629. }
  1630. }
  1631. }
  1632. });
  1633. }
  1634. if(location.href==configPage){
  1635. _GM_addStyle(`
  1636. p>span:nth-child(1),p>span:nth-child(2),p>span:nth-child(3){
  1637. cursor: pointer;
  1638. user-select: none;
  1639. }
  1640. p>span:nth-child(1):hover,p>span:nth-child(2):hover,p>span:nth-child(3):hover{
  1641. color:red;
  1642. }
  1643. .updateDate{
  1644. cursor: pointer;
  1645. user-select: none;
  1646. }
  1647. .updateDate:hover{
  1648. color:red;
  1649. }
  1650. `);
  1651. document.querySelector("[name='user-content-click2import']").innerText=i18n("click2ImportRule")
  1652. configCon=document.querySelector(".markdown-body");
  1653. insertPos=configCon.querySelector("hr");
  1654.  
  1655. if(rulesData.urls && rulesData.urls.length>0){
  1656. document.querySelector("pre[name='user-content-pagetual']").style.display="none";
  1657. document.querySelector("p[name='user-content-click2import']").style.display="none";
  1658. }
  1659. }else return false;
  1660. class Rulebar {
  1661. init(ruleUrl){
  1662. this.ruleUrl=ruleUrl;
  1663. this.item=document.createElement("p");
  1664. this.item.title=ruleUrl.type==0?"AutoPagerize Rules":"Pagetual Rules";
  1665. this.item.dataset.id=this.ruleUrl.id;
  1666. let url=document.createElement("span");
  1667. url.innerHTML=ruleUrl.url;
  1668. let up=document.createElement("span");
  1669. up.innerHTML="↑ ";
  1670. up.title=i18n("sortTitle");
  1671. let down=document.createElement("span");
  1672. down.innerHTML="↓ ";
  1673. down.title=i18n("sortTitle");
  1674. let del=document.createElement("span");
  1675. del.innerHTML="× ";
  1676. up.onclick=e=>{
  1677. this.moveUp();
  1678. };
  1679. down.onclick=e=>{
  1680. this.moveDown();
  1681. };
  1682. del.onclick=e=>{
  1683. this.del();
  1684. };
  1685. this.item.appendChild(up);
  1686. this.item.appendChild(down);
  1687. this.item.appendChild(del);
  1688. this.item.appendChild(url);
  1689. configCon.insertBefore(this.item, insertPos);
  1690. }
  1691. saveSort(){
  1692. let sort=[];
  1693. [].forEach.call(this.item.parentNode.querySelectorAll("p[data-id]"), i=>{
  1694. sort.push(i.dataset.id);
  1695. });
  1696. rulesData.sort=sort;
  1697. storage.setItem("rulesData", rulesData);
  1698. }
  1699. moveUp(){
  1700. let preE=this.item.previousElementSibling;
  1701. if(preE.tagName=="P" && preE.children.length>1){
  1702. this.item.parentNode.insertBefore(this.item,preE);
  1703. this.saveSort();
  1704. }
  1705. }
  1706. moveDown(){
  1707. let nextE=this.item.nextElementSibling;
  1708. if(nextE.tagName=="P" && nextE.children.length>1){
  1709. this.item.parentNode.insertBefore(nextE,this.item);
  1710. this.saveSort();
  1711. }
  1712. }
  1713. del(){
  1714. if(this.ruleUrl.id<2){
  1715. showTips(i18n("cantDel"));
  1716. }else if(window.confirm(i18n("confirmDel"))){
  1717. for(let u=0;u<rulesData.urls.length;u++){
  1718. if(this.ruleUrl.id==rulesData.urls[u].id){
  1719. rulesData.urls.splice(u,1);
  1720. break;
  1721. }
  1722. }
  1723. for(let u=0;u<rulesData.sort.length;u++){
  1724. if(this.ruleUrl.id==rulesData.sort[u]){
  1725. rulesData.sort.splice(u,1);
  1726. break;
  1727. }
  1728. }
  1729. storage.setItem("rulesData", rulesData);
  1730. ruleParser.rules=ruleParser.rules.filter(item=>{return item.from!=this.ruleUrl.id});
  1731. storage.setItem("rules", ruleParser.rules);
  1732. this.item.parentNode.removeChild(this.item);
  1733. //location.reload();
  1734. }
  1735. }
  1736. }
  1737. let updateP=document.createElement("p"),i=0;
  1738. let now=new Date().getTime(),inUpdate=false;
  1739.  
  1740.  
  1741. let pastDate=(new Date(updateDate)).toString(),passStr;
  1742. let passTime=(now-updateDate)/1000;
  1743. if(isNaN(passTime)){
  1744. passStr=i18n("firstUpdate");
  1745. }else if(passTime<60){
  1746. passStr=i18n("passSec", parseInt(passTime))+" ← "+i18n("click2update");
  1747. }else if(passTime<60*60){
  1748. passStr=i18n("passMin", parseInt(passTime/60))+" ← "+i18n("click2update");
  1749. }else if(passTime<60*60*24){
  1750. passStr=i18n("passHour", parseInt(passTime/3600))+" ← "+i18n("click2update");
  1751. }else{
  1752. passStr=i18n("passDay", parseInt(passTime/86400))+" ← "+i18n("click2update");
  1753. }
  1754.  
  1755.  
  1756. updateP.className="updateDate";
  1757. updateP.innerHTML=passStr;
  1758. updateP.title=i18n("update")+" - "+pastDate;
  1759. updateP.onclick=e=>{
  1760. updateRules(()=>{
  1761. showTips(i18n("updateSucc"));
  1762. updateP.innerHTML=i18n("passSec", 0);
  1763. updateP.title=i18n("update");
  1764. },(rule,err)=>{
  1765. showTips("Update "+rule.url+" rules fail!");
  1766. });
  1767. showTips(i18n("beginUpdate"));
  1768. };
  1769. configCon.insertBefore(updateP, insertPos);
  1770. if(ruleUrls){
  1771. ruleUrls.forEach(ruleUrl=>{
  1772. var rulebar=new Rulebar();
  1773. rulebar.init(ruleUrl);
  1774. });
  1775. }
  1776. let customUrlsTitle=document.createElement("h2");
  1777. customUrlsTitle.innerHTML=i18n("customUrls");
  1778. configCon.insertBefore(customUrlsTitle, insertPos);
  1779. let customUrlsInput=document.createElement("textarea");
  1780. customUrlsInput.style.width="100%";
  1781. customUrlsInput.placeholder="0 | http://wedata.net/databases/AutoPagerize/items_all.json";
  1782. configCon.insertBefore(customUrlsInput, insertPos);
  1783.  
  1784. let upBtnImgTitle=document.createElement("h2");
  1785. upBtnImgTitle.innerHTML=i18n("upBtnImg");
  1786. upBtnImgTitle.style.width="50%";
  1787. upBtnImgTitle.style.float="left";
  1788. let upBtnImgInput=document.createElement("input");
  1789. upBtnImgInput.style.width="100%";
  1790. upBtnImgInput.placeholder="data:image/png;base64,UpBtn";
  1791. upBtnImgInput.value=rulesData.upBtnImg||'';
  1792. upBtnImgTitle.appendChild(upBtnImgInput);
  1793. configCon.insertBefore(upBtnImgTitle, insertPos);
  1794.  
  1795. let downBtnImgTitle=document.createElement("h2");
  1796. downBtnImgTitle.innerHTML=i18n("downBtnImg");
  1797. downBtnImgTitle.style.width="50%";
  1798. downBtnImgTitle.style.float="left";
  1799. let downBtnImgInput=document.createElement("input");
  1800. downBtnImgInput.style.width="100%";
  1801. downBtnImgInput.placeholder="data:image/png;base64,DownBtn";
  1802. downBtnImgInput.value=rulesData.downBtnImg||'';
  1803. downBtnImgTitle.appendChild(downBtnImgInput);
  1804. configCon.insertBefore(downBtnImgTitle, insertPos);
  1805.  
  1806. let opacityTitle=document.createElement("h2");
  1807. opacityTitle.innerHTML=i18n("opacity");
  1808. let opacityInput=document.createElement("input");
  1809. opacityInput.value=rulesData.opacity*100;
  1810. opacityInput.type="number";
  1811. opacityInput.style.width="50px";
  1812. opacityInput.style.margin="0 0 0 10px";
  1813. opacityTitle.appendChild(opacityInput);
  1814. configCon.insertBefore(opacityTitle, insertPos);
  1815.  
  1816. let configTable=document.createElement("table");
  1817. configTable.appendChild(document.createElement("tbody"));
  1818. configCon.insertBefore(configTable, insertPos);
  1819. function createCheckbox(innerText, val, tag, parentCheck){
  1820. let title=document.createElement(tag||"h3");
  1821. title.innerHTML=innerText;
  1822. let input=document.createElement("input");
  1823. input.type="checkbox";
  1824. input.style.width="50px";
  1825. input.style.height="20px";
  1826. input.checked=val;
  1827. let tr=document.createElement("tr");
  1828. let td=document.createElement("td");
  1829. td.appendChild(input);
  1830. tr.appendChild(td);
  1831. td=document.createElement("td");
  1832. td.appendChild(title);
  1833. tr.appendChild(td);
  1834. configTable.children[0].appendChild(tr);
  1835. if(parentCheck){
  1836. if(!parentCheck.checked){
  1837. tr.style.display="none";
  1838. }
  1839. parentCheck.addEventListener("click", e=>{
  1840. tr.style.display=parentCheck.checked?"":"none";
  1841. });
  1842. }
  1843. return input;
  1844. }
  1845.  
  1846. let enableWhiteListInput=createCheckbox(i18n("autoRun"), rulesData.enableWhiteList!=true);
  1847. let enableDebugInput=createCheckbox(i18n("enableDebug"), rulesData.enableDebug!=false);
  1848. let enableHistoryInput=createCheckbox(i18n("enableHistory"), rulesData.enableHistory===true);
  1849. let openInNewTabInput=createCheckbox(i18n("openInNewTab"), rulesData.openInNewTab!=false);
  1850. let initRunInput=createCheckbox(i18n("initRun"), rulesData.initRun!=false);
  1851. let preloadInput=createCheckbox(i18n("preload"), rulesData.preload!=false);
  1852. let dbClick2StopInput=createCheckbox(i18n("dbClick2Stop"), rulesData.dbClick2Stop);
  1853. let hideBarInput=createCheckbox("🔲> "+i18n("hideBar"), rulesData.hideBar, "h4", dbClick2StopInput);
  1854. let dbClick2StopCtrlInput=createCheckbox("🔲> "+i18n("dbClick2StopCtrl"), rulesData.dbClick2StopCtrl, "h4", dbClick2StopInput);
  1855. let dbClick2StopAltInput=createCheckbox("🔲> "+i18n("dbClick2StopAlt"), rulesData.dbClick2StopAlt, "h4", dbClick2StopInput);
  1856. let dbClick2StopShiftInput=createCheckbox("🔲> "+i18n("dbClick2StopShift"), rulesData.dbClick2StopShift, "h4", dbClick2StopInput);
  1857. let dbClick2StopMetaInput=createCheckbox("🔲> "+i18n("dbClick2StopMeta"), rulesData.dbClick2StopMeta, "h4", dbClick2StopInput);
  1858.  
  1859. let customRulesTitle=document.createElement("h2");
  1860. customRulesTitle.innerHTML=i18n("customRules");
  1861. configCon.insertBefore(customRulesTitle, insertPos);
  1862. let customRulesInput=document.createElement("textarea");
  1863. configCon.insertBefore(customRulesInput, insertPos);
  1864. if(rulesData.editTemp){
  1865. if(!ruleParser.customRules){
  1866. ruleParser.customRules=[];
  1867. }
  1868. for(let i in ruleParser.customRules){
  1869. if(ruleParser.customRules[i].url==rulesData.editTemp.url){
  1870. ruleParser.customRules.splice(i, 1);
  1871. break;
  1872. }
  1873. }
  1874. ruleParser.customRules.unshift(rulesData.editTemp);
  1875. rulesData.editTemp=null;
  1876. storage.setItem("rulesData", rulesData);
  1877. customRulesInput.scrollIntoView();
  1878. }
  1879. customRulesInput.style.width="100%";
  1880. customRulesInput.style.height="500px";
  1881. 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]`;
  1882. customRulesInput.value=getFormatJSON(ruleParser.customRules);
  1883. let blacklistInput=document.createElement("textarea");
  1884. blacklistInput.style.width="100%";
  1885. blacklistInput.style.height="500px";
  1886. blacklistInput.style.display="none";
  1887. blacklistInput.placeholder="http://*.xxx.com/*/y";
  1888. blacklistInput.value=rulesData.blacklist?rulesData.blacklist.join("\n"):"";
  1889. let blacklistBtn=document.createElement("button");
  1890. blacklistBtn.innerText=i18n("editBlacklist");
  1891. blacklistBtn.style.width="100%";
  1892. blacklistBtn.onclick=e=>{
  1893. blacklistInput.style.display=blacklistInput.style.display=="none"?"":"none";
  1894. };
  1895. configCon.insertBefore(blacklistBtn, insertPos);
  1896. configCon.insertBefore(blacklistInput, insertPos);
  1897. let saveBtn=document.createElement("button");
  1898. saveBtn.innerHTML=i18n("save");
  1899. saveBtn.style.width="100%";
  1900. configCon.insertBefore(saveBtn, insertPos);
  1901. saveBtn.onclick=e=>{
  1902. try{
  1903. storage.setItem("hpRules", []);
  1904. if(customRulesInput.value==""){
  1905. storage.setItem("customRules", "");
  1906. }else{
  1907. let customRules=JSON.parse(customRulesInput.value);
  1908. if(Array && Array.isArray && !Array.isArray(customRules)){
  1909. showTips("Rules must be a Array!");
  1910. return;
  1911. }
  1912. debug(customRules);
  1913. storage.setItem("customRules", customRules);
  1914. }
  1915. }catch(e){
  1916. debug(e);
  1917. showTips("JSON error, check again!");
  1918. return;
  1919. }
  1920. rulesData.opacity=opacityInput.value/100;
  1921. rulesData.blacklist=blacklistInput.value?blacklistInput.value.split("\n"):"";
  1922. rulesData.hideBar=hideBarInput.checked;
  1923. rulesData.dbClick2Stop=dbClick2StopInput.checked;
  1924. rulesData.enableWhiteList=!enableWhiteListInput.checked;
  1925. rulesData.enableDebug=enableDebugInput.checked;
  1926. rulesData.enableHistory=enableHistoryInput.checked;
  1927. rulesData.openInNewTab=openInNewTabInput.checked;
  1928. rulesData.initRun=initRunInput.checked;
  1929. rulesData.preload=preloadInput.checked;
  1930. rulesData.upBtnImg=upBtnImgInput.value;
  1931. rulesData.downBtnImg=downBtnImgInput.value;
  1932. rulesData.dbClick2StopCtrl=dbClick2StopCtrlInput.checked;
  1933. rulesData.dbClick2StopAlt=dbClick2StopAltInput.checked;
  1934. rulesData.dbClick2StopShift=dbClick2StopShiftInput.checked;
  1935. rulesData.dbClick2StopMeta=dbClick2StopMetaInput.checked;
  1936. storage.setItem("rulesData", rulesData);
  1937. let customUrls=customUrlsInput.value.trim();
  1938. if(customUrls){
  1939. customUrls=customUrls.split(/\n/);
  1940. for(let c=0;c<customUrls.length;c++){
  1941. let urlArr=customUrls[c].split("|"),url,type=1;
  1942. if(urlArr.length==1){
  1943. url=urlArr[0].trim();
  1944. if(!/^http/.test(url)){
  1945. showTips("Wrong url, check again!");
  1946. return;
  1947. }
  1948. }else if(urlArr.length==2){
  1949. type=urlArr[0].trim();
  1950. url=urlArr[1].trim();
  1951. if(!/^http/.test(url)){
  1952. showTips("Wrong url, check again!");
  1953. return;
  1954. }
  1955. }else{
  1956. break;
  1957. }
  1958. let maxId=0,hasUrl=false;
  1959. if(!rulesData.urls){
  1960. rulesData.urls=[];
  1961. maxId=1;
  1962. }else{
  1963. rulesData.urls.forEach(u=>{
  1964. if(maxId<u.id){
  1965. maxId=u.id;
  1966. }
  1967. if(u.url==url){
  1968. hasUrl=true;
  1969. }
  1970. });
  1971. if(hasUrl)break;
  1972. }
  1973. if(!rulesData.sort)rulesData.sort=[1];
  1974. rulesData.urls.push({id:maxId+1,url:url,type:type});
  1975. rulesData.sort.push(maxId+1);
  1976. storage.setItem("rulesData", rulesData);
  1977. }
  1978. }
  1979. showTips("The settings are saved");
  1980. location.reload();
  1981. };
  1982. return true;
  1983. }
  1984.  
  1985. var inUpdate=false;
  1986. function updateRules(success,fail){
  1987. if(inUpdate)return;
  1988. inUpdate=true;
  1989. let ruleIndex=ruleUrls.length-1;
  1990. storage.setItem("hpRules", []);
  1991. function addNextRule(){
  1992. if(ruleIndex<0){
  1993. let now=new Date().getTime();
  1994. storage.setItem("ruleLastUpdate", now);
  1995. storage.setItem("rules", ruleParser.rules);
  1996. inUpdate=false;
  1997. success();
  1998. }else{
  1999. let rule=ruleUrls[ruleIndex--];
  2000. ruleParser.addRuleByUrl(rule.url, rule.type, rule.id, (json,err)=>{
  2001. if(!json){
  2002. fail(rule,err);
  2003. }
  2004. addNextRule();
  2005. })
  2006. }
  2007. }
  2008. addNextRule();
  2009. }
  2010.  
  2011. function objIsArr(obj) {
  2012. return obj &&
  2013. typeof obj === 'object' &&
  2014. typeof obj.length === 'number' &&
  2015. !(obj.propertyIsEnumerable('length'));
  2016. }
  2017.  
  2018. function isVisible(el, win) {
  2019. if(!el.offsetParent)return false;
  2020. var loopable = true,
  2021. visible = el.tagName && win.getComputedStyle(el).display != 'none' && win.getComputedStyle(el).visibility != 'hidden';
  2022. while(loopable && visible) {
  2023. el = el.parentNode;
  2024.  
  2025. if(el && el.tagName && el.tagName!="BODY") {
  2026. visible = win.getComputedStyle(el).display != 'none' && win.getComputedStyle(el).visibility != 'hidden';
  2027. }else {
  2028. loopable = false;
  2029. }
  2030. }
  2031. return visible;
  2032. }
  2033.  
  2034. function getElementTop(ele) {
  2035. var actualTop = ele.offsetTop;
  2036. var current = ele.offsetParent;
  2037. while (current) {
  2038. actualTop += current.offsetTop;
  2039. current = current.offsetParent;
  2040. }
  2041. return actualTop;
  2042. }
  2043.  
  2044. function getFormatJSON(obj){
  2045. if(!objIsArr(obj))return "";
  2046. let ret="[\n";
  2047. let len=obj.length,i=0,isLast;
  2048. obj.forEach(item=>{
  2049. ret+=" {\n";
  2050. let iLen=Object.keys(item).length,j=0;
  2051. for(let key in item){
  2052. isLast=(++j)==iLen;
  2053. let value=item[key];
  2054. if(objIsArr(value)){
  2055. let vstr="[",v=0,vIsLast=false;
  2056. value.forEach(vi=>{
  2057. vIsLast=(++v)==value.length;
  2058. vstr+="\""+vi.replace(/\\/g,"\\\\")+"\""+(vIsLast?"":",");
  2059. });
  2060. vstr+="]";
  2061. ret+=" \""+key+"\":"+vstr+""+(isLast?"":",")+"\n";
  2062. }else{
  2063. if(typeof value=="string"){
  2064. value=value.replace(/\\/g,"\\\\").replace(/"/g,"\\\"");
  2065. value="\""+value+"\"";
  2066. }
  2067. ret+=" \""+key+"\":"+value+""+(isLast?"":",")+"\n";
  2068. }
  2069. }
  2070. isLast=(++i)==len;
  2071. ret+=" }"+(isLast?"":",")+"\n";
  2072. });
  2073. ret+="]";
  2074. return ret;
  2075. }
  2076.  
  2077. function globMatch(first, second) {
  2078. if (first.length == 0 && second.length == 0){
  2079. return true;
  2080. }
  2081.  
  2082. if (first.length > 1 && first[0] == '*' &&
  2083. second.length == 0){
  2084. return false;
  2085. }
  2086.  
  2087. if ((first.length > 1 && first[0] == '?') ||
  2088. (first.length != 0 && second.length != 0 &&
  2089. first[0] == second[0])){
  2090. return globMatch(first.substring(1),
  2091. second.substring(1));
  2092. }
  2093.  
  2094. if (first.length > 0 && first[0] == '*'){
  2095. return globMatch(first.substring(1), second) ||
  2096. globMatch(first, second.substring(1));
  2097. }
  2098.  
  2099. return false;
  2100. }
  2101.  
  2102. function initRules(callback) {
  2103. /*0 wedata格式,1 pagetual格式*/
  2104. ruleUrls=[
  2105. {
  2106. id:1,
  2107. url:'http://wedata.net/databases/AutoPagerize/items_all.json',
  2108. type:0,
  2109. }
  2110. ];var i=0,j=0;
  2111.  
  2112. ruleParser.initSavedRules(()=>{
  2113. storage.getItem("rulesData", data=>{
  2114. if(data){
  2115. rulesData=data;
  2116. if(data.urls)ruleUrls=ruleUrls.concat(data.urls);
  2117. if(data.sort){
  2118. let urls=[];
  2119. data.sort.forEach(id=>{
  2120. for(let s=0;s<ruleUrls.length;s++){
  2121. if(id==ruleUrls[s].id){
  2122. urls.push(ruleUrls[s]);
  2123. break;
  2124. }
  2125. }
  2126. });
  2127. ruleUrls=urls;
  2128. }
  2129. }
  2130. if(rulesData.upBtnImg){
  2131. upSvg=`<img src="${rulesData.upBtnImg}"/>`;
  2132. }
  2133. if(rulesData.downBtnImg){
  2134. downSvg=`<img src="${rulesData.downBtnImg}"/>`;
  2135. }
  2136. if(typeof(rulesData.opacity)=="undefined"){
  2137. rulesData.opacity=0.3;
  2138. }
  2139. if(typeof(rulesData.hideBar)=="undefined"){
  2140. rulesData.hideBar=false;
  2141. }
  2142. if(typeof(rulesData.dbClick2Stop)=="undefined"){
  2143. rulesData.dbClick2Stop=true;
  2144. }
  2145. if(typeof(rulesData.enableWhiteList)=="undefined"){
  2146. rulesData.enableWhiteList=false;
  2147. }
  2148. if(typeof(rulesData.enableHistory)=="undefined"){
  2149. rulesData.enableHistory=false;
  2150. }
  2151. if(typeof(rulesData.openInNewTab)=="undefined"){
  2152. rulesData.openInNewTab=true;
  2153. }
  2154. if(typeof(rulesData.enableDebug)=="undefined"){
  2155. rulesData.enableDebug=true;
  2156. }
  2157. if(typeof(rulesData.initRun)=="undefined"){
  2158. rulesData.initRun=true;
  2159. }
  2160. if(typeof(rulesData.preload)=="undefined"){
  2161. rulesData.preload=true;
  2162. }
  2163. if(rulesData.blacklist && rulesData.blacklist.length>0){
  2164. for(let b in rulesData.blacklist){
  2165. let curGlob=rulesData.blacklist[b];
  2166. if(globMatch(curGlob, location.href)){
  2167. return;
  2168. }
  2169. }
  2170. }
  2171. enableDebug=rulesData.enableDebug;
  2172. storage.getItem("forceState_"+location.host, v=>{
  2173. storage.getItem("ruleLastUpdate", date=>{
  2174. if(typeof(v)=="undefined"){
  2175. v=(rulesData.enableWhiteList?1:0);
  2176. }
  2177. forceState=v;
  2178. updateDate=date;
  2179. if(initConfig())return;
  2180. if(forceState==1)return;
  2181. let now=new Date().getTime();
  2182. if(!date || now-date>2*24*60*60*1000){
  2183. updateRules(()=>{
  2184. },(rule,err)=>{});
  2185. }
  2186. callback();
  2187. });
  2188. });
  2189. });
  2190. });
  2191. }
  2192.  
  2193. function requestDoc(url, callback){
  2194. _GM_xmlhttpRequest({
  2195. url: url,
  2196. method: 'GET',
  2197. overrideMimeType: 'text/html;charset='+document.charset,
  2198. headers: {
  2199. 'Referer': location.href,
  2200. "Content-Type": "text/html;charset="+document.charset,
  2201. },
  2202. timeout: 5000,
  2203. onload: function(res) {
  2204. var doc=null,response=res.response;
  2205. let preCode=ruleParser.curSiteRule.pageElementPre || ruleParser.curSiteRule.pagePre;
  2206. if(preCode){
  2207. try{
  2208. response=Function("response",'"use strict";' + preCode)(response);
  2209. }catch(e){
  2210. debug(e);
  2211. }
  2212. }
  2213. try {
  2214. doc=document.implementation.createHTMLDocument('');
  2215. doc.documentElement.innerHTML=response;
  2216. }
  2217. catch (e) {
  2218. debug('parse error'+e.toString());
  2219. }
  2220. let pageElement=ruleParser.getPageElement(doc);
  2221. if(inCors && (!pageElement || pageElement.length==0)){
  2222. ruleParser.curSiteRule.pageElement=allOfBody;
  2223. pageElement=ruleParser.getPageElement(doc);
  2224. ruleParser.getInsert(true);
  2225. }
  2226. //只有1的話怕不是圖片哦
  2227. if(pageElement && (pageElement.length>1 || (pageElement.length==1 && pageElement[0].tagName!="IMG") )){
  2228. let result=ruleParser.insertPage(doc, pageElement, url, callback, false);
  2229. ruleParser.curSiteRule.action=0;
  2230. if(!result){
  2231. ruleParser.curSiteRule.action=1;
  2232. requestFromIframe(url, (doc, eles)=>{
  2233. loadPageOver();
  2234. if(eles){
  2235. ruleParser.insertPage(doc, eles, url, callback, true);
  2236. }
  2237. });
  2238. }
  2239. }else if(ruleParser.curSiteRule.singleUrl || curPage==1){
  2240. ruleParser.curSiteRule.action=1;
  2241. requestFromIframe(url, (doc, eles)=>{
  2242. loadPageOver();
  2243. if(eles){
  2244. ruleParser.insertPage(doc, eles, url, callback, true);
  2245. }
  2246. });
  2247. }else{
  2248. isPause=true;
  2249. callback(false);
  2250. }
  2251. },
  2252. onerror: function(e){
  2253. debug(e);
  2254. callback(false);
  2255. },
  2256. ontimeout: function(e){
  2257. debug(e);
  2258. callback(false);
  2259. }
  2260. });
  2261. }
  2262.  
  2263. var failFromIframe=0;
  2264. var inCors=false;
  2265. function requestFromIframe(url, callback){
  2266. url=url.replace(/#[^#]*/,"");
  2267. let orgPage,curPage;
  2268. let iframe = document.createElement('iframe');
  2269. iframe.name = 'pagetual-iframe';
  2270. iframe.width = '100%';
  2271. iframe.height = '0';
  2272. iframe.frameBorder = '0';
  2273. if(ruleParser.curSiteRule.sandbox!=false){
  2274. iframe.sandbox="allow-same-origin allow-scripts allow-popups allow-forms";
  2275. }
  2276. iframe.style.cssText = 'margin:0!important;padding:0!important;visibility:hidden!important;';
  2277. let waitTime=100,checkEval;
  2278. if(ruleParser.curSiteRule.wait){
  2279. if(isNaN(ruleParser.curSiteRule.wait)){
  2280. try{
  2281. checkEval=Function("doc",'"use strict";' + ruleParser.curSiteRule.wait);
  2282. }catch(e){
  2283. debug(e);
  2284. }
  2285. }else{
  2286. waitTime=ruleParser.curSiteRule.wait;
  2287. }
  2288. }
  2289. let loadedHandler=e=>{
  2290. if(e.data != 'pagetual-iframe:DOMLoaded' && e.type != 'load')return;
  2291. window.removeEventListener('message', loadedHandler, false);
  2292. iframe.removeEventListener('load', loadedHandler, false);
  2293. let tryTimes=0;
  2294. function checkIframe(){
  2295. try{
  2296. let doc=iframe.contentDocument || iframe.contentWindow.document;
  2297. let eles=ruleParser.getPageElement(doc, iframe.contentWindow);
  2298. if(eles && eles.length>0 && (!checkEval || checkEval(doc))){
  2299. callback(doc, eles);
  2300. }else if(tryTimes++ < 10){
  2301. setTimeout(()=>{
  2302. checkIframe();
  2303. },waitTime);
  2304. return;
  2305. }else{
  2306. if(failFromIframe++ > 2){
  2307. failFromIframe=0;
  2308. debug("Stop as failFromIframe");
  2309. isPause=true;
  2310. callback(false, false);
  2311. }else{
  2312. callback(false, false);
  2313. }
  2314. }
  2315. }catch(e){
  2316. debug("Stop as cors");
  2317. inCors=true;
  2318. //isPause=true;
  2319. if(!ruleParser.curSiteRule.pageElement){
  2320. ruleParser.curSiteRule.pageElement=allOfBody;
  2321. ruleParser.getInsert(true);
  2322. }
  2323. ruleParser.curSiteRule.action=0;
  2324. ruleParser.nextLinkHref=url;
  2325. callback(false, false);
  2326. nextPage();
  2327. }
  2328. document.body.removeChild(iframe);
  2329. }
  2330. setTimeout(()=>{
  2331. checkIframe();
  2332. },waitTime);
  2333. };
  2334. window.addEventListener('message', loadedHandler, false);
  2335. iframe.addEventListener('load', loadedHandler, false);
  2336. iframe.src=url;
  2337. document.body.appendChild(iframe);
  2338. }
  2339.  
  2340. function initPage(){
  2341. ruleParser.initPage(()=>{
  2342. if(ruleParser.nextLinkHref){
  2343. let isJs=/^(javascript|#)/.test(ruleParser.nextLinkHref.replace(location.href,""));
  2344. if(!isJs){
  2345. let inForce=(forceState == 2 || forceState == 3);
  2346. _GM_registerMenuCommand(i18n(inForce?"cancelForceIframe":"forceIframe"), ()=>{
  2347. if(inForce){
  2348. storage.setItem("forceState_"+location.host, "");
  2349. }else{
  2350. let _state=ruleParser.curSiteRule.action>0 || confirm(i18n("forceAllBody"))?2:3;
  2351. storage.setItem("forceState_"+location.host, _state);
  2352. }
  2353. location.reload();
  2354. });
  2355. }
  2356. _GM_registerMenuCommand(i18n("loadNow"), ()=>{
  2357. let loadNum=window.prompt(i18n("loadConfirm"), "1");
  2358. if(loadNum==="" || loadNum===null)return;
  2359. autoLoadNum=Math.abs(parseInt(loadNum));
  2360. nextPage();
  2361. });
  2362. }
  2363. initListener();
  2364. if(rulesData.initRun && ruleParser.curSiteRule.initRun!=0)nextPage();
  2365. });
  2366. }
  2367.  
  2368. var pageBarStyle;
  2369. function initView(){
  2370. _GM_addStyle(`
  2371. .pagetual_pageBar.stop {
  2372. -webkit-filter: invert(100%);
  2373. filter: invert(100%);
  2374. opacity: 1!important;
  2375. }
  2376. .pagetual_pageBar.hide {
  2377. display: none!important;
  2378. }
  2379. .pagetual_pageBar:hover {
  2380. opacity: 1!important;
  2381. }
  2382. .pagetual_pageBar span {
  2383. vertical-align: super;
  2384. }
  2385.  
  2386. .pagetual_pageBar span>svg:hover {
  2387. animation: touhouAni 1s infinite;
  2388. }
  2389. .pagetual_pageBar .pagetual_pageNum{
  2390. color: #55555f;
  2391. }
  2392. .pagetual_pageBar .pagetual_pageNum:hover{
  2393. color: #ff6464;
  2394. }
  2395. .pagetual_tipsWords{
  2396. font-size: 50px;
  2397. font-weight: bold;
  2398. font-family: "黑体", -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto",
  2399. "Oxygen", "Ubuntu", "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji",
  2400. "Segoe UI Emoji", "Segoe UI Symbol";
  2401. color: #ffffff;
  2402. height: 70px;
  2403. line-height: 70px;
  2404. position: fixed;
  2405. left: 50%;
  2406. top: 10%;
  2407. margin-left: -150px;
  2408. padding: 0 10px;
  2409. z-index: 999999999;
  2410. background-color: #000;
  2411. border: 1px solid black;
  2412. border-radius: 10px;
  2413. opacity: 0;
  2414. filter: alpha(opacity=65);
  2415. box-shadow: 5px 5px 20px 0px #000;
  2416. -moz-transition:opacity 0.3s ease-in-out 0s;
  2417. -webkit-transition:opacity 0.3s ease-in-out 0s;
  2418. transition:opacity 0.3s ease-in-out 0s;
  2419. pointer-events: none;
  2420. }
  2421.  
  2422. @keyframes touhouAni{
  2423. from {transform: rotate(0deg) scale3d(1.2, 1.2, 1.2);}
  2424. to {transform: rotate(360deg);}
  2425. }
  2426. @-webkit-keyframes touhouAni{
  2427. from {transform: rotate(0deg) scale3d(1.2, 1.2, 1.2);}
  2428. to {transform: rotate(360deg);}
  2429. }
  2430. .pagetual_loading {
  2431. width: 50px;
  2432. height: 50px;
  2433. margin: 10px auto;
  2434. border-radius: 100%;
  2435. -webkit-animation: pagetual_loading_scaleout 1.0s infinite ease-in-out;
  2436. animation: pagetual_loading_scaleout 1.0s infinite ease-in-out;
  2437. }
  2438. @-webkit-keyframes pagetual_loading_scaleout {
  2439. 0% { -webkit-transform: scale(0.0) }
  2440. 100% {
  2441. -webkit-transform: scale(1.0);
  2442. opacity: 0;
  2443. }
  2444. }
  2445. @keyframes pagetual_loading_scaleout {
  2446. 0% {
  2447. transform: scale(0.0);
  2448. -webkit-transform: scale(0.0);
  2449. } 100% {
  2450. transform: scale(1.0);
  2451. -webkit-transform: scale(1.0);
  2452. opacity: 0;
  2453. }
  2454. }
  2455. `);
  2456. pageBarStyle=`line-height:1;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%);font-size: 30px;visibility: visible; position: initial; width: auto; height: 30px; float: none; clear: both; margin: 5px auto; text-align: center;`;
  2457. }
  2458. var loadingDiv=document.createElement("div");
  2459. 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;";
  2460. 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><div class="pagetual_loading"><svg width="50" height="50" style="position:relative;cursor: pointer;width: 50px;height: 50px;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="#6e6e6e" 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="#6e6e6e" p-id="6366"></path></svg></div>`;
  2461. var loadingCSS=`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;`;
  2462.  
  2463. var upSvg=`<svg width="30" height="30" style="display:initial;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>`;
  2464. var upSvgCSS=`display:initial;position:absolute;cursor: pointer;margin: 0 -45px;width: 30px;height: 30px;vertical-align: middle;fill: currentColor;overflow: hidden;`;
  2465. var downSvg=`<svg width="30" height="30" style="display:initial;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>`;
  2466. var downSvgCSS=`display:initial;position:absolute;cursor: pointer;margin: 0 15px;width: 30px;height: 30px;vertical-align: middle;fill: currentColor;overflow: hidden;transform: rotate(180deg);`;
  2467.  
  2468. var initStyle=`display: contents;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;`;
  2469. var pageTextStyle=`line-height: 30px;text-decoration: none;user-select: none;visibility: visible;position: initial;width: auto;max-width: 80%; white-space: nowrap; text-overflow: ellipsis;overflow: hidden;height: auto;float: none;clear: both;margin: 0px auto;text-align: center;display: inline-block;font-weight: bold;font-style: normal;font-size: 16px;letter-spacing: initial;vertical-align: top;color: rgb(85, 85, 95);`;
  2470.  
  2471. var tipsWords=document.createElement("div");
  2472. tipsWords.className="pagetual_tipsWords";
  2473.  
  2474. var isPause=false,isLoading=false,curPage=1,forceState=0,bottomGap=1000,autoLoadNum=-1;
  2475.  
  2476. function changeStop(stop, hide){
  2477. isPause=stop;
  2478. [].forEach.call(document.querySelectorAll(".pagetual_pageBar"), bar=>{
  2479. if(isPause){
  2480. bar.classList.add("stop");
  2481. if(hide)bar.classList.add("hide");
  2482. }else{
  2483. bar.classList.remove("stop");
  2484. if(hide)bar.classList.remove("hide");
  2485. }
  2486. });
  2487. }
  2488.  
  2489. function isInViewPort(element) {
  2490. if(!element.parentNode)return false;
  2491. if(_unsafeWindow.getComputedStyle(element).display=="none")return false;
  2492. const viewWidth = window.innerWidth || document.documentElement.clientWidth;
  2493. const viewHeight = window.innerHeight || document.documentElement.clientHeight;
  2494. const {
  2495. top,
  2496. right,
  2497. bottom,
  2498. left,
  2499. } = element.getBoundingClientRect();
  2500.  
  2501. return (
  2502. top >= 0 &&
  2503. left >= 0 &&
  2504. right <= viewWidth + 1 &&
  2505. bottom <= viewHeight * 2
  2506. );
  2507. }
  2508.  
  2509. var urlChanged=false;
  2510. var _wr = function(type) {
  2511. var orig = history[type];
  2512. return function() {
  2513. var rv = orig.apply(this, arguments);
  2514. var e = new Event(type);
  2515. e.arguments = arguments;
  2516. window.dispatchEvent(e);
  2517. return rv;
  2518. };
  2519. };
  2520. history.pushState = _wr('pushState');
  2521. window.addEventListener('pushState', function(e) {
  2522. urlChanged=true;
  2523. isPause=true;
  2524. setTimeout(()=>{
  2525. if(location.href==configPage){
  2526. location.reload();
  2527. }
  2528. },1);
  2529. });
  2530.  
  2531. function initListener(){
  2532. let loadmoreBtn,loading=true,lastScroll=0,checkLoadMoreTimes=0;
  2533. let checkLoadMore=setInterval(()=>{
  2534. loadmoreBtn=getLoadMore(document);
  2535. if(loadmoreBtn && isVisible(loadmoreBtn, _unsafeWindow)){
  2536. loading=false;
  2537. clearInterval(checkLoadMore);
  2538. }else if(checkLoadMoreTimes>10){
  2539. clearInterval(checkLoadMore);
  2540. }
  2541. },300);
  2542. let checkScrollReach=()=>{
  2543. let scrolly=window.scrollY;
  2544. let windowHeight=window.innerHeight || document.documentElement.clientHeight;
  2545. let scrollH=Math.max(document.documentElement.scrollHeight, document.body.scrollHeight);
  2546. if(scrollH-scrolly-windowHeight<bottomGap){
  2547. nextPage();
  2548. }
  2549. };
  2550. let scrollHandler = e=>{
  2551. if(urlChanged){
  2552. ruleParser.initPage(()=>{
  2553. if(ruleParser.nextLinkHref)initView();
  2554. });
  2555. urlChanged=false;
  2556. isPause=false;
  2557. }
  2558. if(isPause)return;
  2559. if(!loading){
  2560. if(!loadmoreBtn || !loadmoreBtn.parentNode){
  2561. loadmoreBtn=getLoadMore(document);
  2562. }
  2563. if(loadmoreBtn){
  2564. if(isInViewPort(loadmoreBtn)){
  2565. emuClick(loadmoreBtn);
  2566. loading=true;
  2567. setTimeout(()=>{loading=false},200);
  2568. }
  2569. }else{
  2570. loading=true;
  2571. setTimeout(()=>{loading=false},200);
  2572. }
  2573. }
  2574. if(!isLoading){
  2575. checkScrollReach();
  2576. }
  2577. if(ruleParser.curSiteRule.lockScroll){
  2578. let curScroll=document.body.scrollTop||document.documentElement.scrollTop;
  2579. if(lastScroll!=0 && isLoading && Math.abs(lastScroll-curScroll)>100){
  2580. document.body.scrollTop=lastScroll;
  2581. document.documentElement.scrollTop=lastScroll;
  2582. }else{
  2583. lastScroll=curScroll;
  2584. }
  2585. }
  2586. };
  2587. if(!ruleParser.curSiteRule.wheel){
  2588. document.addEventListener('scroll', scrollHandler, true);
  2589. }
  2590. document.addEventListener('wheel', scrollHandler, true);
  2591. document.addEventListener('dblclick', e=>{
  2592. if((rulesData.dbClick2StopCtrl && !e.ctrlKey) ||
  2593. (rulesData.dbClick2StopAlt && !e.altKey) ||
  2594. (rulesData.dbClick2StopShift && !e.shiftKey) ||
  2595. (rulesData.dbClick2StopMeta && !e.metaKey)){
  2596. return;
  2597. }
  2598. if(e.target.tagName!="BODY" && !(rulesData.dbClick2StopCtrl || rulesData.dbClick2StopAlt || rulesData.dbClick2StopShift || rulesData.dbClick2StopMeta)){
  2599. let selStr=document.getSelection().toString().trim();
  2600. if(selStr){
  2601. return;
  2602. }
  2603. }
  2604. if(rulesData.dbClick2Stop && (ruleParser.nextLinkHref || loadmoreBtn)){
  2605. setTimeout(()=>{
  2606. changeStop(!isPause, rulesData.hideBar);
  2607. if(!isPause){
  2608. checkScrollReach();
  2609. }
  2610. showTips(i18n(isPause?"disable":"enable"));
  2611. },10);
  2612. }
  2613. });
  2614. }
  2615.  
  2616. function showTips(content, wordColor, backColor){
  2617. document.body.appendChild(tipsWords);
  2618. tipsWords.style.opacity=0.8;
  2619. tipsWords.innerText=content;
  2620. tipsWords.style.marginLeft=-tipsWords.offsetWidth/2+"px";
  2621. tipsWords.style.color=wordColor||0xFFFFFF;
  2622. tipsWords.style.backgroundColor=backColor||0x000;
  2623. setTimeout(()=>{tipsWords.style.opacity=0},1000);
  2624. }
  2625.  
  2626. function getLoadMore(doc){
  2627. if(ruleParser.curSiteRule.loadMore==="")return null;
  2628. let btnSel=ruleParser.curSiteRule.loadMore||".LoadMore,.load-more,.button-show-more",loadmoreBtn;
  2629. if(btnSel){
  2630. try{
  2631. loadmoreBtn=doc.querySelector(btnSel);
  2632. }catch(e){
  2633. loadmoreBtn=getElementByXpath(btnSel,doc,doc);
  2634. }
  2635. }
  2636. if(!loadmoreBtn){
  2637. let buttons=doc.querySelectorAll("input,button,a,div[onclick]"),loadmoreReg=/^\s*(加载更多|加載更多|load\s*more|もっと読み込む)\s*$/i;
  2638. for(let i=0;i<buttons.length;i++){
  2639. let button=buttons[i];
  2640. if(button && loadmoreReg.test(button.innerText)){
  2641. loadmoreBtn=button;
  2642. break;
  2643. }
  2644. }
  2645. }
  2646. if(loadmoreBtn && !ruleParser.curSiteRule.loadMore && loadmoreBtn.href && !/^(javascript|#)/.test(loadmoreBtn.href))loadmoreBtn=null;
  2647. return loadmoreBtn;
  2648. }
  2649.  
  2650. var hasPageNum=true;
  2651. function createPageBar(url){
  2652. let insert=ruleParser.getInsert();
  2653. if(!insert || !insert.parentNode)return;
  2654. curPage++;
  2655. let example=ruleParser.curSiteRule.insertPos==2?insert.children[0]:(insert.previousElementSibling||insert);
  2656. if(!example || !example.parentNode)example=insert;
  2657. let inTable=example.parentNode.tagName=="TABLE" ||
  2658. example.tagName=="TR" ||
  2659. example.tagName=="TBODY" ||
  2660. (example.previousElementSibling && example.previousElementSibling.tagName=="TR") ||
  2661. (example.previousElementSibling && example.previousElementSibling.tagName=="TBODY");
  2662. let inLi=example.tagName=="LI" || (example.previousElementSibling && example.previousElementSibling.tagName=="LI");
  2663. if(forceState==2){
  2664. inTable=inLi=false;
  2665. }
  2666. let pageBar=document.createElement(inTable?"tr":(inLi?"li":"div"));
  2667. let upSpan=document.createElement("span");
  2668. let downSpan=document.createElement("span");
  2669. let pageText=document.createElement("a");
  2670. let pageNum;
  2671. pageBar.className="pagetual_pageBar";
  2672. pageBar.id="pagetual_pageBar";
  2673. if(isPause){
  2674. pageBar.classList.add("stop");
  2675. }
  2676. pageBar.style.cssText=pageBarStyle;
  2677. pageBar.title=i18n(isPause?"enable":"disable");
  2678. upSpan.innerHTML=upSvg;
  2679. upSpan.children[0].style.cssText=upSvgCSS;
  2680. upSpan.title=i18n("toTop");
  2681. downSpan.innerHTML=downSvg;
  2682. downSpan.children[0].style.cssText=downSvgCSS;
  2683. downSpan.title=i18n("toBottom");
  2684. upSpan.style.cssText=initStyle;
  2685. downSpan.style.cssText=initStyle;
  2686. pageText.href=url;
  2687. pageText.style.cssText=pageTextStyle;
  2688. pageText.title=i18n("current");
  2689. pageBar.appendChild(upSpan);
  2690. pageBar.appendChild(pageText);
  2691. if(ruleParser.nextTitle){
  2692. pageText.innerHTML=ruleParser.nextTitle+" ";
  2693. pageText.title=ruleParser.nextTitle;
  2694. }
  2695. if(ruleParser.curSiteRule.pageNum || (hasPageNum && /[&\/\?](p=|page[=\/_-]?)\d+|[_-]\d+\./.test(url))){
  2696. pageText.innerHTML+="Page ";
  2697. pageNum=document.createElement("span");
  2698. pageNum.innerText=curPage;
  2699. pageNum.className="pagetual_pageNum";
  2700. pageNum.title=i18n("inputPageNum");
  2701. pageNum.style.cssText=pageTextStyle;
  2702. pageNum.style.cursor="pointer";
  2703. pageNum.style.color="";
  2704. pageNum.style.marginLeft="5px";
  2705. pageNum.addEventListener("click", e=>{
  2706. let pageInput=prompt(i18n("inputPageNum"), "1");
  2707. if(pageInput){
  2708. let pageLink=ruleParser.getLinkByPage(url, pageInput);
  2709. if(pageLink){
  2710. _GM_openInTab(pageLink,{active:true});
  2711. }
  2712. }
  2713. e.preventDefault();
  2714. e.stopPropagation();
  2715. });
  2716. pageBar.appendChild(pageNum);
  2717. }else{
  2718. pageText.innerHTML+="Page "+curPage;
  2719. hasPageNum=false;
  2720. }
  2721. pageBar.appendChild(downSpan);
  2722. let parentStyle=_unsafeWindow.getComputedStyle(example.parentNode);
  2723. let parentWidth=example.parentNode.scrollWidth||parseInt(parentStyle.width);
  2724. pageBar.style.width=parentWidth-parseInt(parentStyle.paddingLeft)-parseInt(parentStyle.paddingRight)-10+"px";
  2725. if(parentStyle.display=="grid" || parentStyle.display=="inline-grid"){
  2726. pageBar.style.gridColumnStart=1;
  2727. pageBar.style.gridColumnEnd=1+parseInt(example.parentNode.offsetWidth/example.offsetWidth);
  2728. }
  2729. if(inTable){
  2730. example=(example.tagName=="TR" || example.tagName=="TBODY")?example:example.previousElementSibling;
  2731. if(example.tagName=="TBODY")example=example.querySelector("tr");
  2732. if(example.previousElementSibling)example=example.previousElementSibling;
  2733. let tdNum=0;
  2734. [].forEach.call(example.children, el=>{
  2735. if(el.tagName=="TD" || el.tagName=="TH"){
  2736. tdNum+=el.colSpan||1;
  2737. }
  2738. });
  2739. pageBar.style.display="table-row";
  2740. pageBar.style.backgroundColor="unset";
  2741. pageBar.style.lineHeight="20px";
  2742. pageBar.style.boxShadow="";
  2743. let td=document.createElement("td");
  2744. td.colSpan=tdNum||1;
  2745. let inTd=document.createElement("div");
  2746. inTd.style.backgroundColor="rgb(240 240 240 / 80%)";
  2747. inTd.style.borderRadius="20px";
  2748. inTd.style.padding="0 0";
  2749. inTd.style.margin="10px";
  2750. inTd.style.lineHeight="20px";
  2751. inTd.style.textAlign="center";
  2752. inTd.style.boxShadow="rgb(0 0 0 / 67%) 0px 0px 10px 0px";
  2753. inTd.appendChild(upSpan);
  2754. inTd.appendChild(pageText);
  2755. if(pageNum)inTd.appendChild(pageNum);
  2756. inTd.appendChild(downSpan);
  2757. td.appendChild(inTd);
  2758. pageBar.appendChild(td);
  2759. }else if(inLi){
  2760. example=example.tagName=="LI"?example:example.previousElementSibling;
  2761. pageBar.style.display="table-row";
  2762. pageBar.style.backgroundColor="unset";
  2763. pageBar.style.lineHeight="20px";
  2764. pageBar.style.boxShadow="";
  2765. let td=document.createElement("td");
  2766. td.colSpan=example.children.length;
  2767. let inTd=document.createElement("div");
  2768. inTd.style.backgroundColor="rgb(240 240 240 / 80%)";
  2769. inTd.style.borderRadius="20px";
  2770. inTd.style.margin="10px"
  2771. inTd.style.padding="0 0";
  2772. inTd.style.textAlign="center";
  2773. inTd.style.minWidth="150px";
  2774. inTd.appendChild(upSpan);
  2775. inTd.appendChild(pageText);
  2776. inTd.style.width=parseInt(pageBar.style.width)-20+"px";
  2777. inTd.style.boxShadow="rgb(0 0 0 / 67%) 0px 0px 10px 0px";
  2778. if(pageNum)inTd.appendChild(pageNum);
  2779. inTd.appendChild(downSpan);
  2780. td.appendChild(inTd);
  2781. pageBar.appendChild(td);
  2782. }
  2783.  
  2784. upSpan.addEventListener("click", e=>{
  2785. document.body.scrollTop=0;
  2786. document.documentElement.scrollTop=0;
  2787. e.preventDefault();
  2788. e.stopPropagation();
  2789. });
  2790. downSpan.addEventListener("click", e=>{
  2791. changeStop(true);
  2792. pageBar.title=i18n(isPause?"enable":"disable");
  2793. document.body.scrollTop=9999999;
  2794. document.documentElement.scrollTop=9999999;
  2795. e.preventDefault();
  2796. e.stopPropagation();
  2797. });
  2798. pageBar.addEventListener("click", e=>{
  2799. changeStop(!isPause);
  2800. pageBar.title=i18n(isPause?"enable":"disable");
  2801. });
  2802. pageText.addEventListener("click", e=>{
  2803. e.stopPropagation();
  2804. });
  2805. if(ruleParser.curSiteRule.insertPos==2){
  2806. insert.appendChild(pageBar);
  2807. }else{
  2808. insert.parentNode.insertBefore(pageBar, insert);
  2809. }
  2810. if(ruleParser.curSiteRule.pageBar){
  2811. try{
  2812. Function("pageBar",'"use strict";' + ruleParser.curSiteRule.pageBar)(pageBar);
  2813. }catch(e){
  2814. debug(e);
  2815. }
  2816. }
  2817.  
  2818. let scrollH=Math.max(document.documentElement.scrollHeight, document.body.scrollHeight);
  2819. let posEle=pageBar.nextElementSibling||pageBar;
  2820. while(posEle && !posEle.offsetParent){
  2821. posEle=posEle.previousElementSibling||posEle.parentNode;
  2822. }
  2823. if(posEle){
  2824. let actualTop = getElementTop(posEle);
  2825. bottomGap=scrollH-actualTop+(window.innerHeight||document.documentElement.clientHeight)*(ruleParser.curSiteRule.rate||1);
  2826. if(bottomGap<100)bottomGap=100;
  2827. }else{
  2828. bottomGap=1000;
  2829. }
  2830. if(rulesData.opacity==0)pageBar.style.display="none";
  2831. return pageBar;
  2832. }
  2833.  
  2834. function emuClick(btn){
  2835. if(!PointerEvent)return btn.click();
  2836. let eventParam={
  2837. isTrusted: true,
  2838. altKey: false,
  2839. azimuthAngle: 0,
  2840. bubbles: true,
  2841. button: 0,
  2842. buttons: 0,
  2843. clientX: 1,
  2844. clientY: 1,
  2845. cancelBubble: false,
  2846. cancelable: true,
  2847. composed: true,
  2848. ctrlKey: false,
  2849. defaultPrevented: false,
  2850. detail: 1,
  2851. eventPhase: 2,
  2852. fromElement: null,
  2853. height: 1,
  2854. isPrimary: false,
  2855. metaKey: false,
  2856. pointerId: 1,
  2857. pointerType: "mouse",
  2858. pressure: 0,
  2859. relatedTarget: null,
  2860. returnValue: true,
  2861. shiftKey: false,
  2862. toElement: null,
  2863. twist: 0,
  2864. which: 1
  2865. };
  2866. var mouseEvent = new PointerEvent("mousedown",eventParam);
  2867. btn.dispatchEvent(mouseEvent);
  2868. mouseEvent = new PointerEvent("mouseup",eventParam);
  2869. btn.dispatchEvent(mouseEvent);
  2870. btn.click();
  2871. }
  2872.  
  2873. var emuIframe,lastActiveUrl=location.href;
  2874. function emuPage(callback){
  2875. let orgPage=null,curPage,iframeDoc,times=0,loadmoreBtn,loadmoreEnd=false,waitTimes=10,changed=false;
  2876. function checkPage(){
  2877. if(isPause)return;
  2878. try{
  2879. iframeDoc=emuIframe.contentDocument || emuIframe.contentWindow.document;
  2880. }catch(e){
  2881. debug("Stop as cors");
  2882. isPause=true;
  2883. callback(false, false);
  2884. return;
  2885. }
  2886.  
  2887. let nextLink=ruleParser.getNextLink(iframeDoc);
  2888. let waitTime=200,checkEval;
  2889. if(ruleParser.curSiteRule.wait){
  2890. if(isNaN(ruleParser.curSiteRule.wait)){
  2891. try{
  2892. checkEval=Function("doc",'"use strict";' + ruleParser.curSiteRule.wait);
  2893. }catch(e){
  2894. debug(e);
  2895. }
  2896. }else{
  2897. waitTime=ruleParser.curSiteRule.wait;
  2898. }
  2899. }
  2900.  
  2901. if(!orgPage){
  2902. if(!loadmoreEnd){
  2903. loadmoreBtn=getLoadMore(iframeDoc);
  2904. if(loadmoreBtn && isVisible(loadmoreBtn, iframeDoc.defaultView)){
  2905. emuClick(loadmoreBtn);
  2906. let intv=setInterval(()=>{
  2907. loadmoreBtn=getLoadMore(iframeDoc);
  2908. if(!loadmoreBtn || !loadmoreBtn.parentNode || !isVisible(loadmoreBtn, iframeDoc.defaultView)){
  2909. clearInterval(intv);
  2910. loadmoreEnd=true;
  2911. setTimeout(()=>{
  2912. checkPage();
  2913. },500);
  2914. }else{
  2915. emuClick(loadmoreBtn);
  2916. }
  2917. },200);
  2918. return;
  2919. }else{
  2920. loadmoreEnd=true;
  2921. }
  2922. }
  2923. let pageEle=ruleParser.getPageElement(iframeDoc, iframeDoc.defaultView, true);
  2924. if(!nextLink || !pageEle || pageEle.length==0 || (checkEval && !checkEval(iframeDoc))){
  2925. if(waitTimes-->0){
  2926. setTimeout(()=>{
  2927. checkPage();
  2928. },waitTime);
  2929. return;
  2930. }
  2931. }
  2932. orgPage=pageEle;
  2933. if(!orgPage || orgPage.length==0){
  2934. debug("Stop as no page when emu");
  2935. isPause=true;
  2936. callback(false, false);
  2937. return;
  2938. }
  2939. if(orgPage && orgPage[0].tagName=="UL")orgPage=orgPage[0].children;
  2940. if(orgPage && nextLink){
  2941. orgPage=orgPage[parseInt(orgPage.length/2)];
  2942. if(!isVisible(nextLink, iframeDoc.defaultView)){
  2943. debug("Stop as next hide when emu");
  2944. isPause=true;
  2945. callback(false, false);
  2946. }else{
  2947. emuClick(nextLink);
  2948. setTimeout(()=>{
  2949. checkPage();
  2950. },500);
  2951. }
  2952. }else{
  2953. debug("Stop as no next when emu");
  2954. isPause=true;
  2955. callback(false, false);
  2956. }
  2957. return;
  2958. }
  2959. if(times++ > 20){
  2960. debug("Stop as timeout when emu");
  2961. isPause=true;
  2962. callback(false, false);
  2963. return;
  2964. }
  2965. let eles=ruleParser.getPageElement(iframeDoc, iframeDoc.defaultView, true),checkItem;
  2966. if(eles && eles.length>0){
  2967. checkItem=eles;
  2968. if(eles[0].tagName=="UL"){
  2969. checkItem=eles[0].children;
  2970. }
  2971. checkItem=checkItem[parseInt(checkItem.length/2)];
  2972. }
  2973. if(!checkItem || (checkEval && !checkEval(iframeDoc))){
  2974. setTimeout(()=>{
  2975. checkPage();
  2976. },waitTime);
  2977. }else{
  2978. if(orgPage!=checkItem){
  2979. changed=true;
  2980. orgPage=checkItem;
  2981. setTimeout(()=>{
  2982. checkPage();
  2983. },waitTime);
  2984. }else if(changed){
  2985. callback(iframeDoc, eles);
  2986. }else{
  2987. setTimeout(()=>{
  2988. checkPage();
  2989. },waitTime);
  2990. }
  2991. }
  2992. }
  2993. if(!emuIframe){
  2994. let loaded=false;
  2995. emuIframe = document.createElement('iframe');
  2996. emuIframe.name = 'pagetual-iframe';
  2997. if(ruleParser.curSiteRule.sandbox!=false){
  2998. emuIframe.sandbox="allow-same-origin allow-scripts allow-popups allow-forms";
  2999. }
  3000. emuIframe.width = '100%';
  3001. emuIframe.height = '0';
  3002. emuIframe.frameBorder = '0';
  3003. emuIframe.style.cssText = 'margin:0!important;padding:0!important;visibility:hidden!important;';
  3004. emuIframe.addEventListener("load", e=>{
  3005. setTimeout(()=>{
  3006. try{
  3007. iframeDoc=emuIframe.contentDocument || emuIframe.contentWindow.document;
  3008. }catch(e){
  3009. debug("Stop as cors");
  3010. isPause=true;
  3011. callback(false, false);
  3012. return;
  3013. }
  3014. let code=ruleParser.curSiteRule.init;
  3015. if(code){
  3016. try{
  3017. Function('doc','win','iframe','"use strict";' + code)(iframeDoc, iframeDoc.defaultView, emuIframe);
  3018. }catch(e){
  3019. debug(e);
  3020. }
  3021. }
  3022. if(loaded)return;
  3023. loaded=true;
  3024. checkPage();
  3025. },500);
  3026. });
  3027. emuIframe.src=lastActiveUrl.replace(/#[^#]*/,"");
  3028. document.body.appendChild(emuIframe);
  3029. }else{
  3030. checkPage();
  3031. }
  3032. }
  3033.  
  3034. var scrollToResizeInited = false;
  3035. var resizePool = [];
  3036. function scrollToResize() {
  3037. if (scrollToResizeInited) return;
  3038. scrollToResizeInited = true;
  3039. var scrollingToResize = false;
  3040. document.addEventListener("scroll", e => {
  3041. if (scrollingToResize) return;
  3042. else {
  3043. scrollingToResize = true;
  3044. setTimeout(() => {scrollingToResize = false}, 500);
  3045. }
  3046. resizePool.forEach(resizeArr => {
  3047. let iframe = resizeArr[1]();
  3048. let frameDoc = resizeArr[2]();
  3049. if(ruleParser.curSiteRule.singleUrl){
  3050. iframe.style.height=frameDoc.body.scrollHeight+"px";
  3051. iframe.style.width=frameDoc.body.scrollWidth+"px";
  3052. }else{
  3053. let pageEle = resizeArr[0]();
  3054. if(pageEle){
  3055. let targetElement = pageEle[0];
  3056. if(pageEle.length > 1){
  3057. targetElement = targetElement.parentNode;
  3058. }
  3059. iframe.style.height=targetElement.scrollHeight+"px";
  3060. frameDoc.documentElement.scrollTop = 0;
  3061. frameDoc.documentElement.scrollLeft = 0;
  3062. while(targetElement && targetElement.offsetParent){
  3063. targetElement.offsetParent.scrollTop = targetElement.offsetTop;
  3064. if(targetElement.offsetParent.scrollTop == 0){
  3065. frameDoc.documentElement.scrollTop += targetElement.offsetTop;
  3066. }
  3067. targetElement.offsetParent.scrollLeft = targetElement.offsetLeft;
  3068. if(targetElement.offsetParent.scrollLeft == 0){
  3069. frameDoc.documentElement.scrollLeft += targetElement.offsetLeft;
  3070. }
  3071. targetElement = targetElement.offsetParent;
  3072. }
  3073. }
  3074. }
  3075. });
  3076. });
  3077. }
  3078.  
  3079. function forceIframe(url, callback){
  3080. url=url.replace(/#[^#]*/,"");
  3081. let curIframe = document.createElement('iframe'),iframeDoc;
  3082. let setPosition = ()=>{
  3083. let getIframe = () => {
  3084. return curIframe;
  3085. };
  3086. let getFrameDoc = () => {
  3087. return iframeDoc;
  3088. };
  3089. if(ruleParser.curSiteRule.singleUrl){
  3090. resizePool.push([() => {}, getIframe, getFrameDoc]);
  3091. }else{
  3092. let pageElement = ruleParser.getPageElement(iframeDoc,iframeDoc.defaultView);
  3093. let getPageEle = () => {
  3094. if (!pageElement) {
  3095. pageElement = ruleParser.getPageElement(iframeDoc,iframeDoc.defaultView);
  3096. }
  3097. return pageElement;
  3098. };
  3099. resizePool.push([getPageEle, getIframe, getFrameDoc]);
  3100. }
  3101. };
  3102. curIframe.name = 'pagetual-iframe';
  3103. curIframe.sandbox="allow-same-origin allow-scripts allow-popups allow-forms";
  3104. curIframe.frameBorder = '0';
  3105. curIframe.scrolling="no";
  3106. 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;';
  3107. curIframe.addEventListener("load", e=>{
  3108. try{
  3109. iframeDoc=curIframe.contentDocument || curIframe.contentWindow.document;
  3110. }catch(e){
  3111. debug("Stop as cors");
  3112. isPause=true;
  3113. callback(false, false);
  3114. return;
  3115. }
  3116. ruleParser.insertPage(iframeDoc, [], url, null, true);
  3117. callback(curIframe, true);
  3118. let css=ruleParser.curSiteRule.css;
  3119. if(css){
  3120. let styleEle=iframeDoc.createElement("style");
  3121. styleEle.innerHTML=css;
  3122. iframeDoc.head.appendChild(styleEle);
  3123. }
  3124. setPosition();
  3125. let code=ruleParser.curSiteRule.init;
  3126. if(code){
  3127. try{
  3128. Function('doc','win','iframe','"use strict";' + code)(iframeDoc,iframeDoc.defaultView,curIframe);
  3129. }catch(e){
  3130. debug(e);
  3131. }
  3132. }
  3133. });
  3134. let inAction=false,checkTimes=0;
  3135. let forceRefresh=e=>{
  3136. if(inAction || !iframeDoc)return;
  3137. inAction=true;
  3138. let foundNext=()=>{
  3139. document.removeEventListener("scroll", forceRefresh);
  3140. }
  3141. setTimeout(()=>{
  3142. inAction=false;
  3143. if(!ruleParser.nextLinkHref){
  3144. checkTimes++;
  3145. ruleParser.getNextLink(iframeDoc);
  3146. if(ruleParser.nextLinkHref){
  3147. foundNext();
  3148. }else if(checkTimes>=10){
  3149. foundNext();
  3150. }
  3151. }else{
  3152. foundNext();
  3153. }
  3154. },50);
  3155. };
  3156. document.addEventListener("scroll", forceRefresh);
  3157. curIframe.src=url;
  3158. let insert=ruleParser.getInsert();
  3159. if(ruleParser.curSiteRule.singleUrl){
  3160. document.body.appendChild(curIframe);
  3161. }else if(ruleParser.curSiteRule.insertPos==2){
  3162. ruleParser.insert.appendChild(curIframe);
  3163. }else{
  3164. ruleParser.insert.parentNode.insertBefore(curIframe, ruleParser.insert);
  3165. }
  3166. scrollToResize();
  3167. return curIframe;
  3168. }
  3169.  
  3170. function loadPageOver(){
  3171. isLoading=false;
  3172. if(loadingDiv.parentNode){
  3173. loadingDiv.parentNode.removeChild(loadingDiv);
  3174. }
  3175. /*setTimeout(()=>{
  3176. let scrollH=Math.max(document.documentElement.scrollHeight, document.body.scrollHeight);
  3177. if(scrollH <= (window.innerHeight || document.documentElement.clientHeight)){
  3178. nextPage();
  3179. }
  3180. },1);*/
  3181. }
  3182.  
  3183. var tryTimes = 0;
  3184.  
  3185. function nextPage(){
  3186. if(isPause || isLoading)return;
  3187. if(ruleParser.curSiteRule.delay){
  3188. try{
  3189. let checkDelay=Function('"use strict";' + ruleParser.curSiteRule.delay)();
  3190. if(!checkDelay)return;
  3191. }catch(e){
  3192. debug(e);
  3193. }
  3194. }
  3195. let nextLink=ruleParser.nextLinkHref;
  3196. if(!nextLink){
  3197. if(curPage==1){
  3198. ruleParser.getNextLink(document);
  3199. nextLink=ruleParser.nextLinkHref;
  3200. }
  3201. if(!nextLink){
  3202. isPause=true;
  3203. if(curPage==1 && (ruleParser.curSiteRule.pinUrl || tryTimes++ <= 10)){
  3204. setTimeout(()=>{isPause=false},500);
  3205. }
  3206. return;
  3207. }
  3208. }
  3209. let pvGallery=document.querySelector("span.pv-gallery-container");
  3210. if(pvGallery && pvGallery.style.display!="none")return;
  3211. let insert=ruleParser.getInsert();
  3212. if(insert){
  3213. let isJs=/^(javascript|#)/.test(nextLink.replace(location.href,""));
  3214. if(!isJs){
  3215. emuIframe=null;
  3216. lastActiveUrl=nextLink;
  3217. }
  3218. if(location.protocol=="https:" && /^http:/.test(nextLink)){
  3219. nextLink=nextLink.replace(/^http/,"https");
  3220. }
  3221. isLoading=true;
  3222. document.body.appendChild(loadingDiv);
  3223. loadingDiv.style.cssText=loadingCSS;
  3224. let sleep=ruleParser.curSiteRule.sleep||0;
  3225. setTimeout(()=>{
  3226. if(ruleParser.curSiteRule.pageElementByJs){
  3227. var over=ele=>{
  3228. loadPageOver();
  3229. if(ele){
  3230. createPageBar(nextLink);
  3231. ruleParser.insertPage(null, ele, nextLink, null, true);
  3232. if(autoLoadNum>=0){
  3233. if(autoLoadNum!=0 && --autoLoadNum==0){
  3234. autoLoadNum=-1;
  3235. }else{
  3236. nextPage();
  3237. }
  3238. }
  3239. }else{
  3240. debug("Stop as no page when get by js");
  3241. isPause=true;
  3242. }
  3243. };
  3244. try{
  3245. Function("over",'"use strict";' + ruleParser.curSiteRule.pageElementByJs)(over);
  3246. }catch(e){
  3247. debug(e);
  3248. }
  3249. }else if((forceState==3||ruleParser.curSiteRule.action==1) && !isJs){
  3250. requestFromIframe(nextLink, (doc, eles)=>{
  3251. loadPageOver();
  3252. if(eles){
  3253. ruleParser.insertPage(doc, eles, nextLink, ()=>{
  3254. createPageBar(nextLink);
  3255. }, true);
  3256. if(autoLoadNum>=0){
  3257. if(autoLoadNum!=0 && --autoLoadNum==0){
  3258. autoLoadNum=-1;
  3259. }else{
  3260. nextPage();
  3261. }
  3262. }
  3263. }
  3264. });
  3265. }else if((forceState==2||ruleParser.curSiteRule.action==2) && !isJs){
  3266. forceIframe(nextLink, (iframe, eles)=>{
  3267. loadPageOver();
  3268. let pageBar=createPageBar(nextLink);
  3269. if(pageBar)iframe.parentNode.insertBefore(pageBar, iframe);
  3270. if(autoLoadNum>=0){
  3271. if(autoLoadNum!=0 && --autoLoadNum==0){
  3272. autoLoadNum=-1;
  3273. }else{
  3274. nextPage();
  3275. }
  3276. }
  3277. });
  3278. }else{
  3279. if(!isJs){
  3280. requestDoc(nextLink, (eles)=>{
  3281. loadPageOver();
  3282. if(eles){
  3283. createPageBar(nextLink);
  3284. if(autoLoadNum>=0){
  3285. if(autoLoadNum!=0 && --autoLoadNum==0){
  3286. autoLoadNum=-1;
  3287. }else{
  3288. nextPage();
  3289. }
  3290. }
  3291. }
  3292. });
  3293. }else{
  3294. emuPage((doc, eles)=>{
  3295. loadPageOver();
  3296. if(eles){
  3297. ruleParser.insertPage(doc, eles, "", ()=>{
  3298. createPageBar(nextLink);
  3299. }, true);
  3300. if(autoLoadNum>=0){
  3301. if(autoLoadNum!=0 && --autoLoadNum==0){
  3302. autoLoadNum=-1;
  3303. }else{
  3304. nextPage();
  3305. }
  3306. }
  3307. }
  3308. });
  3309. }
  3310. }
  3311. },sleep);
  3312. }
  3313. }
  3314.  
  3315. function init(){
  3316. initRules(()=>{
  3317. initPage();
  3318. });
  3319. }
  3320. setTimeout(()=>{
  3321. init();
  3322. },100);
  3323. })();