V2EX 增强

自动签到、链接转图片、自动无缝翻页、使用 SOV2EX 搜索、回到顶部(右键点击两侧空白处)、快速回复(左键双击两侧空白处)、新标签页打开链接、标签页伪装为 Github(摸鱼)

当前为 2023-05-19 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name V2EX 增强
  3. // @version 1.2.0
  4. // @author X.I.U
  5. // @description 自动签到、链接转图片、自动无缝翻页、使用 SOV2EX 搜索、回到顶部(右键点击两侧空白处)、快速回复(左键双击两侧空白处)、新标签页打开链接、标签页伪装为 Github(摸鱼)
  6. // @match *://v2ex.com/*
  7. // @match *://*.v2ex.com/*
  8. // @match *://www.sov2ex.com/*
  9. // @icon data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAOGVYSWZNTQAqAAAACAABh2kABAAAAAEAAAAaAAAAAAACoAIABAAAAAEAAAAgoAMABAAAAAEAAAAgAAAAAI9OQMkAAARKSURBVHicrVe7SzNLFP/t7CObbEg0WliJooUxcAsfYKFW2lh8NhdLwUIsbMTCBG3EIoid4J/xNd9t7ZSAIiJcNaSIYBcbNVlMsq/M3MK762YziVE8EGbYOTnnd55zRsD/xBiT7+/vf+u6vlir1VTLskApFfADRAhhiqIgEokYsVjsNJVK/S0Igg0AAgAUCoW/np+fr15fX5WfUPgZ9fT0WP39/dNjY2P/SowxOZfLXZXLZUVRFIyPjyORSCAUCkEQmh3AGIMgCGCMAYC3D/IFiVIKy7Lw8vKCfD6PcrmsALhijEWFu7u7P4+Pj78URcHMzAyi0WjXCoPnQeLxV6tVXFxcwLIsDA0N/UN0XV8EgGQyCU3TQClFo9FAo9EAY8xb/Xv33OWllIJSCsaYt/L4GWPQNA3JZBIAoOv6olSr1VQASCQS3h/9FgWtC54FPcDbB2UkEgkAQK1WUyXLsgAAiqK0MFNKIQgCKKVcl3ajMChPFEXIsgwAsCwLkltq/jh1K/C7RAhxAQmSX3DQwo2NDZydnbWcu4D9vKFQCNvb21hdXfUU8ZIwaIQHwD3w50Aul/PQflZyjuPg6OgIoVAIKysrbRUGc6wFgH8lhLRV2K4Es9ksotEolpaWuuobTSEAPhIPACSpCV/XtL+/D03TMD8/3ySP5xHiB+BnYIxBFEUQQkAI8faiKHJ/fh7GGPb29nB9fd0kryOAIBAXgCRJkCQJhBBv5QGSJKmJ33EcpNNp5PP5JpnBkHXMgcvLy65cXiqVsLm5iaenp6bvpmkinU7j+PgYw8PD3BJuCgEAr+kEAXXqCQMDAzg5OUFfX19LaN7e3pDJZGDbNtcLXA+4ICzL6nj5uHu3WtwwBIn3rQVAJws/6/WlUgmZTAa6rnvKXHDxeByHh4cghHgXFRcAT8Hy8nLXVy/P0nA4jGw2i8HBQTiO09kDfgD+PvDdWUCWZRwcHGB0dBTuhcczkhsCfyfslvwACSHY3d1FKpXy8oinvAlAEATw7tLPEjB4DgBbW1uYnJyEYRhfb8V+hJ0AtPPA+vo6ZmdnYZpmizy3urruhFNTU17n83dDf9dz6z0cDmNtbQ0LCwswDKNpNON1QK4Hgi7a2dnh/qkdMcZgmmbbCYo7DxBCGKVU4CWh/ybjCQwqNwyD2zWDSdhoNAC8P1gkWZZhmiYsy4KiKCCEeAz1ev1LpfdZqYqiCMaY1xNkWQZRVdUAgHK5/PHxY2bzVv/eb43fa/7RPMhPCPGGUVeXqqqGFI1GTyuVyq9isQhN0xCJRBAKhbqy8KvE2PvDpFgsAgA0TTsVGGPy+fn5m67riizLGBkZQTweh6Io31YUJEopbNtGpVLBw8MDbNtGLBaz5ubmopIgCPbt7e00gCtd15VCofAjSjtRLBazent7pwVBsD0TGWPyzc3N72q1uliv11XHcX70eS7LMlRVNSKRyOnExIT3PP8P91unlxYYZf4AAAAASUVORK5CYII=
  10. // @grant GM_xmlhttpRequest
  11. // @grant GM_registerMenuCommand
  12. // @grant GM_unregisterMenuCommand
  13. // @grant GM_openInTab
  14. // @grant GM_getValue
  15. // @grant GM_setValue
  16. // @grant GM_notification
  17. // @license GPL-3.0 License
  18. // @run-at document-end
  19. // @namespace https://github.com/XIU2/UserScript
  20. // @supportURL https://github.com/XIU2/UserScript
  21. // @homepageURL https://github.com/XIU2/UserScript
  22. // ==/UserScript==
  23.  
  24. (function() {
  25. 'use strict';
  26. var menu_ALL = [
  27. ['menu_autoClockIn', '自动签到', '自动签到', true],
  28. ['menu_linksToImgs', '链接转图片', '链接转图片', true],
  29. ['menu_pageLoading', '自动无缝翻页', '自动无缝翻页', true],
  30. ['menu_pageLoading_reply', '帖子内自动翻页', '帖子内自动翻页', false],
  31. ['menu_backToTop', '回到顶部(右键点击两侧空白处)', '回到顶部', true],
  32. ['menu_quickReply', '快速回复(左键双击两侧空白处)', '快速回复', true],
  33. ['menu_linksBlank', '新标签页打开链接', '新标签页打开链接', true],
  34. ['menu_sov2ex', '使用 SOV2EX 搜索', '使用 SOV2EX 搜索', false],
  35. ['menu_fish', '标签页伪装为 Github(摸鱼)', '标签页伪装为 Github', false]
  36. ], menu_ID = [], pausePage = true;
  37. for (let i=0;i<menu_ALL.length;i++){ // 如果读取到的值为 null 就写入默认值
  38. if (GM_getValue(menu_ALL[i][0]) == null){GM_setValue(menu_ALL[i][0], menu_ALL[i][3])};
  39. }
  40.  
  41. registerMenuCommand();
  42.  
  43. // 注册脚本菜单
  44. function registerMenuCommand() {
  45. if (menu_ID.length > menu_ALL.length){ // 如果菜单ID数组多于菜单数组,说明不是首次添加菜单,需要卸载所有脚本菜单
  46. for (let i=0;i<menu_ID.length;i++){
  47. GM_unregisterMenuCommand(menu_ID[i]);
  48. }
  49. }
  50. for (let i=0;i<menu_ALL.length;i++){ // 循环注册脚本菜单
  51. menu_ALL[i][3] = GM_getValue(menu_ALL[i][0]);
  52. menu_ID[i] = GM_registerMenuCommand(`${menu_ALL[i][3]?'✅':'❌'} ${menu_ALL[i][1]}`, function(){menu_switch(`${menu_ALL[i][3]}`,`${menu_ALL[i][0]}`,`${menu_ALL[i][2]}`)});
  53. }
  54. menu_ID[menu_ID.length] = GM_registerMenuCommand('💬 反馈 & 建议', function () {window.GM_openInTab('https://github.com/XIU2/UserScript#xiu2userscript', {active: true,insert: true,setParent: true});window.GM_openInTab('https://greasyfork.org/zh-CN/scripts/424246/feedback', {active: true,insert: true,setParent: true});});
  55. }
  56.  
  57. // 菜单开关
  58. function menu_switch(menu_status, Name, Tips) {
  59. if (menu_status == 'true'){
  60. GM_setValue(`${Name}`, false);
  61. GM_notification({text: `已关闭 [${Tips}] 功能\n(点击刷新网页后生效)`, timeout: 3500, onclick: function(){location.reload();}});
  62. }else{
  63. GM_setValue(`${Name}`, true);
  64. GM_notification({text: `已开启 [${Tips}] 功能\n(点击刷新网页后生效)`, timeout: 3500, onclick: function(){location.reload();}});
  65. }
  66. registerMenuCommand(); // 重新注册脚本菜单
  67. };
  68.  
  69. // 返回菜单值
  70. function menu_value(menuName) {
  71. for (let menu of menu_ALL) {
  72. if (menu[0] == menuName) {
  73. return menu[3]
  74. }
  75. }
  76. }
  77.  
  78.  
  79. // 默认 ID 为 0
  80. var curSite = {SiteTypeID: 0};
  81.  
  82. // 自动翻页规则
  83. let DBSite = {
  84. recent: { // 最近主题页
  85. SiteTypeID: 1,
  86. pager: {
  87. type: 1,
  88. nextLink: '//a[@class="page_current"]/following-sibling::a[1][@href]',
  89. pageElement: 'css;.cell.item',
  90. HT_insert: ['//div[@id="Main"]//div[@class="box"]//div[@class="cell"][last()]', 1],
  91. replaceE: 'css;#Main > .box > .cell[style]:not(.item) > table',
  92. scrollDelta: 1500
  93. }
  94. },
  95. notifications: { // 提醒消息页
  96. SiteTypeID: 2,
  97. pager: {
  98. type: 1,
  99. nextLink: '//a[@class="page_current"]/following-sibling::a[1][@href]',
  100. pageElement: 'css;#notifications > div',
  101. HT_insert: ['css;#notifications', 3],
  102. replaceE: 'css;#Main > .box > .cell[style] > table',
  103. scrollDelta: 1500
  104. }
  105. },
  106. replies: { // 用户回复页
  107. SiteTypeID: 3,
  108. pager: {
  109. type: 1,
  110. nextLink: '//a[@class="page_current"]/following-sibling::a[1][@href]',
  111. pageElement: '//div[@id="Main"]//div[@class="box"]//div[@class="dock_area"] | //*[@id="Main"]//div[@class="box"]//div[@class="inner"] | //*[@id="Main"]//div[@class="box"]//div[@class="dock_area"][last()]/following-sibling::div[@class="cell"][1]',
  112. HT_insert: ['//div[@id="Main"]//div[@class="box"]//div[@class="cell"][last()]', 1],
  113. replaceE: 'css;#Main > .box > .cell[style] > table',
  114. scrollDelta: 1500
  115. }
  116. },
  117. go: { // 分类主题页
  118. SiteTypeID: 4,
  119. pager: {
  120. type: 1,
  121. nextLink: '//a[@class="page_current"]/following-sibling::a[1][@href]',
  122. pageElement: 'css;#TopicsNode > div',
  123. HT_insert: ['css;#TopicsNode', 3],
  124. replaceE: 'css;#Main > .box > .cell[style] > table',
  125. scrollDelta: 1500
  126. }
  127. },
  128. reply: { // 帖子内容页(从前往后)
  129. SiteTypeID: 5,
  130. pager: {
  131. type: 1,
  132. nextLink: '//a[@class="page_current"]/following-sibling::a[1][@href]',
  133. pageElement: 'css;.cell[id^="r_"]',
  134. HT_insert: ['//div[starts-with(@id, "r_")][last()]/following-sibling::div[@class="cell"][1]', 1],
  135. replaceE: 'css;#Main > .box > .cell[style] > table',
  136. scrollDelta: 1500
  137. }
  138. },
  139. reply_positive: { // 帖子内容页(从后往前)
  140. SiteTypeID: 6,
  141. pager: {
  142. type: 1,
  143. nextLink: '//a[@class="page_current"]/preceding-sibling::a[1][@href]',
  144. pageElement: 'css;.cell[id^="r_"]',
  145. HT_insert: ['//div[starts-with(@id, "r_")][1]', 1],
  146. replaceE: 'css;#Main > .box > .cell[style] > table',
  147. scrollDelta: 1500
  148. }
  149. },
  150. balance: { // 账户余额页
  151. SiteTypeID: 7,
  152. pager: {
  153. type: 1,
  154. nextLink: '//a[@class="page_current"]/following-sibling::a[1][@href]',
  155. pageElement: 'css;#Main .box > div:not(.cell) > table > tbody > tr:not(:first-child)',
  156. HT_insert: ['css;#Main .box > div:not(.cell) > table > tbody', 3],
  157. replaceE: 'css;#Main > .box > .cell[style] > table',
  158. scrollDelta: 1000
  159. }
  160. },
  161. sov2ex: { // sov2ex
  162. SiteTypeID: 8,
  163. pager: {
  164. nextLink: '.paging>a',
  165. scrollDelta: 1000
  166. }
  167. }
  168. };
  169.  
  170. if (location.hostname === 'www.sov2ex.com') {
  171. curSite = DBSite.sov2ex;
  172. pageLoading();
  173. } else {
  174. switch (location.pathname) {
  175. case '/': // 首页
  176. addChangesLink();
  177. break;
  178. case '/recent': // 最近主题页
  179. curSite = DBSite.recent;
  180. break;
  181. case '/notifications': // 提醒消息页
  182. curSite = DBSite.notifications;
  183. break;
  184. case '/balance': // 账户余额页
  185. curSite = DBSite.balance;
  186. break;
  187. default:
  188. if (location.pathname.indexOf('/go/') > -1) { // 分类主题页
  189. curSite = DBSite.go;
  190. } else if (location.pathname.indexOf('/t/') > -1) { // 帖子内容页
  191. if(menu_value('menu_pageLoading_reply'))curSite = DBSite.reply; // 帖子内自动无缝翻页
  192. if(menu_value('menu_quickReply'))quickReply(); // 快速回复(双击左右两侧空白处)
  193. } else if (location.pathname.indexOf('/replies') > -1) { // 用户回复页
  194. curSite = DBSite.replies;
  195. }
  196. }
  197.  
  198. curSite.pageUrl = ''; // 下一页URL
  199. if(menu_value('menu_linksBlank')) linksBlank(); // 新标签页打开链接
  200. if(menu_value('menu_fish')) fish(); // 标签页伪装为 Github(摸鱼)
  201. if(menu_value('menu_autoClockIn')) setTimeout(qianDao, 1000); // 自动签到(后台),延迟 1 秒执行是为了兼容 [V2ex Plus] 扩展
  202. if(menu_value('menu_pageLoading')) pageLoading(); // 自动翻页(无缝)
  203. if(menu_value('menu_backToTop')) backToTop(); // 回到顶部(右键点击左右两侧空白处)
  204. if(menu_value('menu_linksToImgs')) linksToImgs(); // 链接转图片
  205. if(menu_value('menu_sov2ex')) setTimeout(soV2ex, 1000); // 替换为 sov2ex 搜索
  206. }
  207.  
  208. // 自动签到(后台)
  209. function qianDao() {
  210. let timeNow = new Date().getUTCFullYear() + '/' + (new Date().getUTCMonth() + 1) + '/' + new Date().getUTCDate() // 当前 UTC-0 时间(V2EX 按这个时间的)
  211. if (location.pathname == '/') { // 在首页
  212. let qiandao = document.querySelector('.box .inner a[href="/mission/daily"]');
  213. if (qiandao) { // 如果找到了签到提示
  214. qianDao_(qiandao, timeNow); // 后台签到
  215. } else if (document.getElementById('gift_v2excellent')) { // 兼容 [V2ex Plus] 扩展
  216. document.getElementById('gift_v2excellent').click();
  217. GM_setValue('menu_clockInTime', timeNow); // 写入签到时间以供后续比较
  218. console.info('[V2EX 增强] 自动签到完成!')
  219. } else { // 都没有找到,说明已经签过到了
  220. console.info('[V2EX 增强] 已经签过到了。')
  221. }
  222. } else { // 不在首页
  223. let timeOld = GM_getValue('menu_clockInTime')
  224. if (!timeOld || timeOld != timeNow) {
  225. qianDaoStatus_(timeNow) // 后台获取签到状态(并判断是否需要签到)
  226. }/* else { // 新旧签到时间一致
  227. console.info('[V2EX 增强] 已经签过到了。')
  228. }*/
  229. }
  230. }
  231.  
  232.  
  233. // 后台签到
  234. function qianDao_(qiandao, timeNow) {
  235. let url = (location.origin + "/mission/daily/redeem?" + RegExp("once\\=(\\d+)").exec(document.querySelector('div#Top .tools, #menu-body').innerHTML)[0]);
  236. GM_xmlhttpRequest({
  237. url: url,
  238. method: 'GET',
  239. timeout: 5000,
  240. onload: function (response) {
  241. let html = ShowPager.createDocumentByString(response.responseText);
  242. //console.log(html)
  243. if (html.querySelector('li.fa.fa-ok-sign')) {
  244. html = html.getElementById('Main').textContent.match(/已连续登录 (\d+?) 天/)[0];
  245. GM_setValue('menu_clockInTime', timeNow); // 写入签到时间以供后续比较
  246. console.info('[V2EX 增强] 自动签到完成!')
  247. if (qiandao) {
  248. qiandao.textContent = `自动签到完成!${html}`;
  249. qiandao.href = 'javascript:void(0);';
  250. }
  251. } else {
  252. GM_notification({text: '自动签到失败!请访问 V2EX 首页试试。\n如果连续几天都签到失败,请联系作者解决!', timeout: 4000, onclick() {window.GM_openInTab('https://github.com/XIU2/UserScript#xiu2userscript', {active: true,insert: true,setParent: true});window.GM_openInTab('https://greasyfork.org/zh-CN/scripts/424246/feedback', {active: true,insert: true,setParent: true});}});
  253. console.warn('[V2EX 增强] 自动签到失败!请访问 V2EX 首页试试。如果连续几天都签到失败,请联系作者解决!')
  254. if (qiandao) qiandao.textContent = '自动签到失败!请尝试手动签到!';
  255. }
  256. }
  257. });
  258. }
  259.  
  260.  
  261. // 后台获取签到状态(并判断是否需要签到)
  262. function qianDaoStatus_(timeNow) {
  263. GM_xmlhttpRequest({
  264. url: 'https://www.v2ex.com/mission/daily',
  265. method: 'GET',
  266. timeout: 5000,
  267. onload: function (response) {
  268. let html = ShowPager.createDocumentByString(response.responseText);
  269. if (html.querySelector('input[value^="领取"]')) { // 还没有签到...
  270. qianDao_(null, timeNow); // 后台签到
  271. } else { // 已经签到了...
  272. console.info('[V2EX 增强] 已经签过到了。')
  273. GM_setValue('menu_clockInTime', timeNow); // 写入签到时间以供后续比较
  274. }
  275. }
  276. });
  277. }
  278.  
  279.  
  280. // 替换为 sov2ex 搜索,代码来自 v2ex-plus 扩展:https://github.com/sciooga/v2ex-plus (懒得重复造轮子了~
  281. function soV2ex() {
  282. document.body.appendChild(document.createElement('script')).textContent = `
  283. var $search = $('#search')
  284. var searchEvents = $._data($search[0], "events" )
  285. var oKeydownEvent = searchEvents['keydown'][0]['handler']
  286. var oInputEvent = searchEvents['input'][0]['handler']
  287. $search.attr("placeholder","sov2ex")
  288. $search.unbind('keydown', oKeydownEvent)
  289. $search.unbind('input', oInputEvent)
  290. $search.on('input', function(e) {
  291. oInputEvent(e)
  292. $('.search-item:last').attr('href', 'https://www.sov2ex.com/?q=' + $search.val()).text('sov2ex ' +$search.val());
  293. })
  294. $search.keydown(function(e) {
  295. if (e.code == 'Enter' || e.code == 'NumpadEnter' || e.keyCode === 13) {
  296. if ($('.search-item:last').is('.active')) {
  297. $(this).val($(this).val().replace(/[#%&]/g,""));//用户输入不能包含特殊字符#%&
  298. window.open("https://www.sov2ex.com/?q=" + $(this).val());
  299. return 0
  300. }
  301. }
  302. oKeydownEvent(e)
  303. })
  304. `;
  305. }
  306.  
  307.  
  308. // 回到顶部(右键左右两侧空白处)
  309. function backToTop() {
  310. document.getElementById('Wrapper').oncontextmenu = document.querySelector('#Wrapper > .content').oncontextmenu = function(event){
  311. if (event.target == this) {
  312. event.preventDefault();
  313. window.scrollTo(0,0)
  314. }
  315. }
  316. }
  317.  
  318.  
  319. // 标签页伪装为 Github(摸鱼)
  320. function fish() {
  321. window.document.title = 'GitHub'
  322. if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
  323. document.querySelector("link[rel*='shortcut icon']").href = 'https://github.githubassets.com/favicons/favicon-dark.png'
  324. } else {
  325. document.querySelector("link[rel*='shortcut icon']").href = 'https://github.githubassets.com/favicons/favicon.png'
  326. }
  327. }
  328.  
  329.  
  330. // 链接转图片
  331. function linksToImgs() {
  332. let links = document.links;
  333. Array.from(links).forEach(function (_this) {
  334. if (/^https.*\.(?:jpg|jpeg|jpe|bmp|png|gif)/i.test(_this.href) && !(/<img\s/i.test(_this.innerHTML))) {
  335. _this.innerHTML = `<img src="${_this.href}" style="max-width: 100%!important;" />`;
  336. } else if (/^https:\/\/imgur\.com\/[a-z]+$/i.test(_this.href)) { // 针对没有文件后缀的 imgur 图床链接
  337. _this.innerHTML = `<img src="${_this.href}.png" style="max-width: 100%!important;" />`;
  338. }
  339. });
  340. }
  341.  
  342.  
  343. // 快速回复(双击左右两侧空白处)
  344. function quickReply() {
  345. document.getElementById('Wrapper').ondblclick = document.querySelector('#Wrapper > .content').ondblclick = function(event){
  346. if (event.target==this) {
  347. if (document.querySelector('.box.reply-box-sticky')) {
  348. document.getElementById('undock-button').click();
  349. } else {
  350. let _top = document.body.scrollTop + document.documentElement.scrollTop;
  351. document.getElementById('reply_content').focus();
  352. window.scrollTo(0,_top);console.log(_top);
  353. }
  354. }
  355. }
  356. }
  357.  
  358.  
  359. // 新标签页打开链接
  360. function linksBlank() {
  361. if (location.pathname.indexOf('/settings') > -1) return
  362. document.head.appendChild(document.createElement('base')).target = '_blank'; // 让所有链接默认以新标签页打开
  363. Array.from(document.links).forEach(function (_this) {
  364. if (_this.onclick || _this.href.slice(0,4) != 'http' || _this.href.indexOf('#;') > -1 || _this.href.indexOf('night/toggle') > -1 || _this.href.indexOf('/favorite') > -1 || _this.href.indexOf('/?tab=') > -1) {
  365. _this.target = '_self'
  366. }
  367. })
  368. document.querySelectorAll('form').forEach(function (_this) {
  369. if (!_this.target) {_this.target = '_self'}
  370. });
  371.  
  372. const callback = (mutationsList, observer) => {
  373. for (const mutation of mutationsList) {
  374. for (const target of mutation.addedNodes) {
  375. if (target.nodeType != 1) return
  376. if (target.tagName === 'A') {
  377. if (target.onclick || target.href.slice(0,4) != 'http' || target.href.indexOf('#;') > -1 || target.href.indexOf('night/toggle') > -1 || target.href.indexOf('/favorite') > -1) {
  378. target.target = '_self'
  379. }
  380. } else {
  381. document.querySelectorAll('a').forEach(function (_this) {
  382. if (_this.onclick || _this.href.slice(0,4) != 'http' || _this.href.indexOf('#;') > -1 || _this.href.indexOf('night/toggle') > -1 || _this.href.indexOf('/favorite') > -1) {
  383. _this.target = '_self'
  384. }
  385. });
  386. }
  387. }
  388. }
  389. };
  390. const observer = new MutationObserver(callback);
  391. observer.observe(document, { childList: true, subtree: true });
  392. }
  393.  
  394.  
  395. // 添加全站最近更新主题链接
  396. function addChangesLink() {
  397. let links = document.querySelector('#Main .box .inner:last-child');if (!links) return
  398. links.innerHTML = `<div style="float: left;"><span class="chevron">»</span> &nbsp;<a href="/recent" target="_blank">更多新主题</a></div><div style="text-align: right;"><a href="/changes" target="_blank" style="text-align: right;">全站最近更新主题</a> &nbsp;<span class="chevron">«</span></div>`
  399. }
  400.  
  401.  
  402. // 自动无缝翻页
  403. function pageLoading() {
  404. if (curSite.SiteTypeID > 0){
  405. windowScroll(function (direction, e) {
  406. // 下滑 且 未暂停翻页 且 SiteTypeID > 0 时,才准备翻页
  407. if (direction != 'down' || !pausePage) return
  408. let scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop,
  409. scrollHeight = window.innerHeight || document.documentElement.clientHeight,
  410. scrollDelta = curSite.pager.scrollDelta;
  411. if (document.documentElement.scrollHeight <= scrollHeight + scrollTop + scrollDelta) {
  412. if (curSite.pager.type === 1) {
  413. ShowPager.loadMorePage();
  414. }else{
  415. let autopbn = document.querySelector(curSite.pager.nextLink);
  416. if (autopbn){
  417. autopbn.click();
  418. pausePage = false
  419. setTimeout(function(){pausePage = true;}, 500)
  420. }
  421. }
  422. }
  423. });
  424. }
  425. }
  426.  
  427.  
  428. // 滚动条事件
  429. function windowScroll(fn1) {
  430. var beforeScrollTop = document.documentElement.scrollTop || document.body.scrollTop,
  431. fn = fn1 || function () {};
  432. setTimeout(function () { // 延时执行,避免刚载入到页面就触发翻页事件
  433. window.addEventListener('scroll', function (e) {
  434. var afterScrollTop = document.documentElement.scrollTop || document.body.scrollTop,
  435. delta = afterScrollTop - beforeScrollTop;
  436. if (delta == 0) return false;
  437. fn(delta > 0 ? 'down' : 'up', e);
  438. beforeScrollTop = afterScrollTop;
  439. }, false);
  440. }, 1000)
  441. }
  442.  
  443.  
  444. // 修改自 https://greasyfork.org/scripts/14178 , https://github.com/machsix/Super-preloader
  445. var ShowPager = {
  446. getFullHref: function (e) {
  447. if (e != null && e.nodeType === 1 && e.href && e.href.slice(0,4) === 'http') return e.href;
  448. return '';
  449. },
  450. createDocumentByString: function (e) {
  451. if (e) {
  452. if ('HTML' !== document.documentElement.nodeName) return (new DOMParser).parseFromString(e, 'application/xhtml+xml');
  453. var t;
  454. try { t = (new DOMParser).parseFromString(e, 'text/html');} catch (e) {}
  455. if (t) return t;
  456. if (document.implementation.createHTMLDocument) {
  457. t = document.implementation.createHTMLDocument('ADocument');
  458. } else {
  459. try {((t = document.cloneNode(!1)).appendChild(t.importNode(document.documentElement, !1)), t.documentElement.appendChild(t.createElement('head')), t.documentElement.appendChild(t.createElement('body')));} catch (e) {}
  460. }
  461. if (t) {
  462. var r = document.createRange(),
  463. n = r.createContextualFragment(e);
  464. r.selectNodeContents(document.body);
  465. t.body.appendChild(n);
  466. for (var a, o = { TITLE: !0, META: !0, LINK: !0, STYLE: !0, BASE: !0}, i = t.body, s = i.childNodes, c = s.length - 1; c >= 0; c--) o[(a = s[c]).nodeName] && i.removeChild(a);
  467. return t;
  468. }
  469. } else console.error('没有找到要转成 DOM 的字符串');
  470. },
  471. loadMorePage: function () {
  472. if (curSite.pager) {
  473. let curPageEle = getElementByXpath(curSite.pager.nextLink);
  474. var url = this.getFullHref(curPageEle);
  475. console.log(`${url} ${curPageEle} ${curSite.pageUrl}`);
  476. if(url === '') return;
  477. if(curSite.pageUrl === url) return;// 不会重复加载相同的页面
  478. curSite.pageUrl = url;
  479. // 读取下一页的数据
  480. curSite.pager.startFilter && curSite.pager.startFilter();
  481. GM_xmlhttpRequest({
  482. url: url,
  483. method: "GET",
  484. timeout: 5000,
  485. onload: function (response) {
  486. try {
  487. var newBody = ShowPager.createDocumentByString(response.responseText);
  488. let pageElems = getAllElements(curSite.pager.pageElement, newBody, newBody);
  489. let toElement = getAllElements(curSite.pager.HT_insert[0])[0];
  490. if (pageElems.length >= 0) {
  491. // 如果有插入前函数就执行函数
  492. if (curSite.function && curSite.function.before) {
  493. if (curSite.function.parameter) { // 如果指定了参数
  494. pageElems = curSite.function.before(curSite.function.parameter);
  495. }else{
  496. pageElems = curSite.function.before(pageElems);
  497. }
  498. }
  499. // 插入位置
  500. let addTo;
  501. switch (curSite.pager.HT_insert[1]) {
  502. case 1:
  503. addTo = "beforebegin"
  504. break;
  505. case 2:
  506. addTo = "afterbegin"
  507. break;
  508. case 3:
  509. addTo = "beforeend"
  510. break;
  511. case 4:
  512. addTo = "afterend"
  513. break;
  514. }
  515. // 插入新页面元素
  516. pageElems.forEach(function (one) {
  517. toElement.insertAdjacentElement(addTo, one);
  518. });
  519. // 替换待替换元素
  520. try {
  521. let oriE = getAllElements(curSite.pager.replaceE);
  522. let repE = getAllElements(curSite.pager.replaceE, newBody, newBody);
  523. if (oriE.length === repE.length) {
  524. for (var i = 0; i < oriE.length; i++) {
  525. oriE[i].outerHTML = repE[i].outerHTML;
  526. }
  527. }
  528. } catch (e) {
  529. console.log(e);
  530. }
  531. // 如果有插入后函数就执行函数
  532. if (curSite.function && curSite.function.after) {
  533. if (curSite.function.parameter) { // 如果指定了参数
  534. curSite.function.after(curSite.function.parameter);
  535. }else{
  536. curSite.function.after();
  537. }
  538. }
  539. }
  540. } catch (e) {
  541. console.log(e);
  542. }
  543. }
  544. });
  545. }
  546. },
  547. };
  548. function getElementByCSS(css, contextNode = document) {
  549. return contextNode.querySelector(css);
  550. }
  551. function getAllElementsByCSS(css, contextNode = document) {
  552. return [].slice.call(contextNode.querySelectorAll(css));
  553. }
  554. function getElementByXpath(xpath, contextNode, doc = document) {
  555. contextNode = contextNode || doc;
  556. try {
  557. const result = doc.evaluate(xpath, contextNode, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
  558. // 应该总是返回一个元素节点
  559. return result.singleNodeValue && result.singleNodeValue.nodeType === 1 && result.singleNodeValue;
  560. } catch (err) {
  561. throw new Error(`Invalid xpath: ${xpath}`);
  562. }
  563. }
  564. function getAllElementsByXpath(xpath, contextNode, doc = document) {
  565. contextNode = contextNode || doc;
  566. const result = [];
  567. try {
  568. const query = doc.evaluate(xpath, contextNode, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  569. for (let i = 0; i < query.snapshotLength; i++) {
  570. const node = query.snapshotItem(i);
  571. // 如果是 Element 节点
  572. if (node.nodeType === 1) result.push(node);
  573. }
  574. } catch (err) {
  575. throw new Error(`无效 Xpath: ${xpath}`);
  576. }
  577. return result;
  578. }
  579. function getAllElements(selector, contextNode = undefined, doc = document, win = window, _cplink = undefined) {
  580. if (!selector) return [];
  581. contextNode = contextNode || doc;
  582. if (typeof selector === 'string') {
  583. if (selector.search(/^css;/i) === 0) {
  584. return getAllElementsByCSS(selector.slice(4), contextNode);
  585. } else {
  586. return getAllElementsByXpath(selector, contextNode, doc);
  587. }
  588. } else {
  589. const query = selector(doc, win, _cplink);
  590. if (!Array.isArray(query)) {
  591. throw new Error('getAllElements 返回错误类型');
  592. } else {
  593. return query;
  594. }
  595. }
  596. }
  597. })();