V2EX 增强

自动签到、自动无缝翻页、回到顶部(右键点击两侧空白处)

当前为 2021-04-01 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name V2EX 增强
  3. // @version 1.0.1
  4. // @author X.I.U
  5. // @description 自动签到、自动无缝翻页、回到顶部(右键点击两侧空白处)
  6. // @match *://v2ex.com/*
  7. // @match *://*.v2ex.com/*
  8. // @icon https://www.v2ex.com/static/favicon.ico
  9. // @grant GM_xmlhttpRequest
  10. // @grant GM_registerMenuCommand
  11. // @grant GM_unregisterMenuCommand
  12. // @grant GM_openInTab
  13. // @grant GM_getValue
  14. // @grant GM_setValue
  15. // @grant GM_notification
  16. // @license GPL-3.0 License
  17. // @run-at document-end
  18. // @namespace https://github.com/XIU2/UserScript
  19. // ==/UserScript==
  20.  
  21. (function() {
  22. var menu_ALL = [
  23. ['menu_autoClockIn', '自动签到', '自动签到', true],
  24. ['menu_pageLoading', '自动无缝翻页', '自动无缝翻页', true],
  25. ['menu_pageLoading_reply', '帖子内自动翻页', '帖子内自动翻页', false],
  26. ['menu_backToTop', '回到顶部(右键点击两侧空白处)', '回到顶部', true]
  27. ], menu_ID = [];
  28. for (let i=0;i<menu_ALL.length;i++){ // 如果读取到的值为 null 就写入默认值
  29. if (GM_getValue(menu_ALL[i][0]) == null){GM_setValue(menu_ALL[i][0], menu_ALL[i][3])};
  30. }
  31. registerMenuCommand();
  32.  
  33. // 注册脚本菜单
  34. function registerMenuCommand() {
  35. if (menu_ID.length > menu_ALL.length){ // 如果菜单ID数组多于菜单数组,说明不是首次添加菜单,需要卸载所有脚本菜单
  36. for (let i=0;i<menu_ID.length;i++){
  37. GM_unregisterMenuCommand(menu_ID[i]);
  38. }
  39. }
  40. for (let i=0;i<menu_ALL.length;i++){ // 循环注册脚本菜单
  41. menu_ALL[i][3] = GM_getValue(menu_ALL[i][0]);
  42. 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]}`)});
  43. }
  44. 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});});
  45. }
  46.  
  47. // 菜单开关
  48. function menu_switch(menu_status, Name, Tips) {
  49. if (menu_status == 'true'){
  50. GM_setValue(`${Name}`, false);
  51. GM_notification({text: `已关闭 [${Tips}] 功能\n(刷新网页后生效)`, title: '吾爱破解论坛增强', timeout: 3000});
  52. }else{
  53. GM_setValue(`${Name}`, true);
  54. GM_notification({text: `已开启 [${Tips}] 功能\n(刷新网页后生效)`, title: '吾爱破解论坛增强', timeout: 3000});
  55. }
  56. registerMenuCommand(); // 重新注册脚本菜单
  57. };
  58.  
  59. // 返回菜单值
  60. function menu_value(menuName) {
  61. for (let menu of menu_ALL) {
  62. if (menu[0] == menuName) {
  63. return menu[3]
  64. }
  65. }
  66. }
  67.  
  68.  
  69. // 默认 ID 为 0
  70. var curSite = {SiteTypeID: 0};
  71.  
  72. // 自动翻页规则
  73. // HT_insert:1 = 插入该元素的前面;2 = 插入该元素内的最后面
  74. // scrollDelta:数值越大,滚动条触发点越靠上(越早开始翻页),一般是访问网页速度越慢,该值就需要越大
  75. let DBSite = {
  76. recent: { // 最近主题页
  77. SiteTypeID: 1,
  78. pager: {
  79. type: 1,
  80. nextLink: '//a[@class="page_current"]/following-sibling::a[1][@href]',
  81. pageElement: 'css;.cell.item',
  82. HT_insert: ['//*[@id="Main"]//div[@class="box"]//div[@class="cell"][last()]', 1],
  83. replaceE: 'css;#Main .box .cell:not(.item) > table',
  84. scrollDelta: 600
  85. }
  86. },
  87. notifications: { // 提醒消息页
  88. SiteTypeID: 2,
  89. pager: {
  90. type: 1,
  91. nextLink: '//a[@class="page_current"]/following-sibling::a[1][@href]',
  92. pageElement: 'css;#notifications > div',
  93. HT_insert: ['css;#notifications', 2],
  94. replaceE: 'css;#Main .box > .cell:not(.item) > table',
  95. scrollDelta: 600
  96. }
  97. },
  98. replies: { // 用户回复页
  99. SiteTypeID: 3,
  100. pager: {
  101. type: 1,
  102. nextLink: '//a[@class="page_current"]/following-sibling::a[1][@href]',
  103. pageElement: '//*[@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]',
  104. HT_insert: ['//*[@id="Main"]//div[@class="box"]//div[@class="cell"][last()]', 1],
  105. replaceE: 'css;#Main .box .cell:not(.item) > table',
  106. scrollDelta: 1000
  107. }
  108. },
  109. go: { // 分类主题页
  110. SiteTypeID: 4,
  111. pager: {
  112. type: 1,
  113. nextLink: '//a[@class="page_current"]/following-sibling::a[1][@href]',
  114. pageElement: 'css;#TopicsNode > div',
  115. HT_insert: ['css;#TopicsNode', 2],
  116. replaceE: 'css;#Main .box > .cell:not(.item) > table',
  117. scrollDelta: 700
  118. }
  119. },
  120. reply: { // 帖子内容页
  121. SiteTypeID: 5,
  122. pager: {
  123. type: 1,
  124. nextLink: '//a[@class="page_current"]/preceding-sibling::a[1][@href]',
  125. pageElement: 'css;.cell[id^="r_"]',
  126. HT_insert: ['//div[starts-with(@id, "r_")][last()]/following-sibling::div[@class="cell"][1]', 1],
  127. replaceE: 'css;#Main .box > .cell:not(.normalUser) > table',
  128. scrollDelta: 700
  129. }
  130. },
  131. reply_positive: { // 帖子内容页(正序)
  132. SiteTypeID: 6,
  133. pager: {
  134. type: 1,
  135. nextLink: '//a[@class="page_current"]/preceding-sibling::a[1][@href]',
  136. pageElement: 'css;.cell[id^="r_"]',
  137. HT_insert: ['//div[starts-with(@id, "r_")][position()=1]', 1],
  138. replaceE: 'css;#Main .box > .cell:not(.normalUser) > table',
  139. scrollDelta: 700
  140. }
  141. }
  142. };
  143.  
  144.  
  145. switch (location.pathname) {
  146. case "/recent": // 最近主题页
  147. curSite = DBSite.recent;
  148. break;
  149. case "/notifications": // 提醒消息页
  150. curSite = DBSite.notifications;
  151. break;
  152. default:
  153. if (location.pathname.indexOf('/go/') > -1) { // 分类主题页
  154. curSite = DBSite.go;
  155. } else if (location.pathname.indexOf('/t/') > -1) { // 帖子内容页
  156. if(menu_value('menu_pageLoading_reply'))curSite = DBSite.reply_positive; // 帖子内自动无缝翻页
  157. } else if (location.pathname.indexOf('/replies') > -1) { // 用户回复页
  158. curSite = DBSite.replies;
  159. }
  160. }
  161.  
  162. curSite.pageUrl = ""; // 下一页URL
  163. if(menu_value('menu_autoClockIn'))setTimeout(qianDao, 1000) // 自动签到(后台),延迟 1 秒执行是为了兼容 [V2ex Plus] 扩展
  164. if(menu_value('menu_pageLoading'))pageLoading(); // 自动翻页(无缝)
  165. if(menu_value('menu_backToTop'))backToTop(); // 回到顶部(右键点击空白处)
  166.  
  167.  
  168. // 自动签到(后台)
  169. function qianDao() {
  170. let qiandao = document.querySelector('.box .inner a[href="/mission/daily"]');
  171. if (qiandao) {
  172. let url = (location.origin + "/mission/daily/redeem?" + RegExp("once\\=(\\d+)").exec(document.querySelector('div#Top .tools').innerHTML)[0]);
  173. GM_xmlhttpRequest({
  174. url: url,
  175. method: "GET",
  176. timeout: 5000,
  177. onload: function (response) {
  178. let html = ShowPager.createDocumentByString(response.responseText);
  179. console.log(html)
  180. if (html.querySelector('li.fa.fa-ok-sign')) {
  181. html = html.getElementById('Main').innerText.match(/已连续登录 (\d+?) 天/)[0];
  182. qiandao.innerText = `自动签到成功!${html}`;
  183. qiandao.href = '#';
  184. } else {
  185. GM_notification({text: '自动签到失败!请联系作者解决!', 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});}});
  186. qiandao.innerText = '自动签到失败!请尝试手动签到!';
  187. }
  188. }
  189. });
  190. } else if (document.getElementById('gift_v2excellent')) { // 兼容 [V2ex Plus] 扩展
  191. document.getElementById('gift_v2excellent').click();
  192. }
  193. }
  194.  
  195.  
  196. // 回到顶部(右键点击空白处)
  197. function backToTop() {
  198. document.getElementById("Wrapper").oncontextmenu = function(event){
  199. if (event.target==this) {
  200. event.preventDefault();
  201. window.scrollTo(0,0)
  202. }
  203. }
  204. }
  205.  
  206.  
  207. // 自动无缝翻页
  208. function pageLoading() {
  209. if (curSite.SiteTypeID > 0){
  210. windowScroll(function (direction, e) {
  211. if (direction === "down") { // 下滑才准备翻页
  212. let scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
  213. //console.log(document.documentElement.scrollHeight)
  214. let scrollDelta = curSite.pager.scrollDelta;
  215. if (document.documentElement.scrollHeight <= document.documentElement.clientHeight + scrollTop + scrollDelta) {
  216. if (curSite.pager.type === 1) {
  217. ShowPager.loadMorePage();
  218. }else{
  219. let autopbn = document.querySelector(curSite.pager.nextLink);
  220. if (autopbn){
  221. autopbn.click();
  222. }
  223. }
  224. }
  225. }
  226. });
  227. }
  228. }
  229.  
  230.  
  231. // 滚动条事件
  232. function windowScroll(fn1) {
  233. var beforeScrollTop = document.documentElement.scrollTop,
  234. fn = fn1 || function () {};
  235. setTimeout(function () { // 延时执行,避免刚载入到页面就触发翻页事件
  236. window.addEventListener("scroll", function (e) {
  237. var afterScrollTop = document.documentElement.scrollTop,
  238. delta = afterScrollTop - beforeScrollTop;
  239. if (delta == 0) return false;
  240. fn(delta > 0 ? "down" : "up", e);
  241. beforeScrollTop = afterScrollTop;
  242. }, false);
  243. }, 1000)
  244. }
  245.  
  246.  
  247. var ShowPager = { // 修改自 https://greasyfork.org/scripts/14178
  248. getFullHref: function (e) {
  249. if(e == null) return '';
  250. "string" != typeof e && (e = e.getAttribute("href"));
  251. var t = this.getFullHref.a;
  252. return t || (this.getFullHref.a = t = document.createElement("a")), t.href = e, t.href;
  253. },
  254. createDocumentByString: function (e) {
  255. if (e) {
  256. if ("HTML" !== document.documentElement.nodeName) return (new DOMParser).parseFromString(e, "application/xhtml+xml");
  257. var t;
  258. try {
  259. t = (new DOMParser).parseFromString(e, "text/html");
  260. } catch (e) {
  261. }
  262. if (t) return t;
  263. if (document.implementation.createHTMLDocument) t = document.implementation.createHTMLDocument("ADocument"); else try {
  264. (t = document.cloneNode(!1)).appendChild(t.importNode(document.documentElement, !1)),
  265. t.documentElement.appendChild(t.createElement("head")), t.documentElement.appendChild(t.createElement("body"));
  266. } catch (e) {
  267. }
  268. if (t) {
  269. var r = document.createRange();
  270. r.selectNodeContents(document.body);
  271. var n = r.createContextualFragment(e);
  272. t.body.appendChild(n);
  273. for (var a, o = {
  274. TITLE: !0,
  275. META: !0,
  276. LINK: !0,
  277. STYLE: !0,
  278. BASE: !0
  279. }, i = t.body, s = i.childNodes, c = s.length - 1; c >= 0; c--) o[(a = s[c]).nodeName] && i.removeChild(a);
  280. return t;
  281. }
  282. } else console.error("没有找到要转成DOM的字符串");
  283. },
  284. loadMorePage: function () {
  285. if (curSite.pager) {
  286. let curPageEle = getElementByXpath(curSite.pager.nextLink);
  287. var url = this.getFullHref(curPageEle);
  288. //console.log(`${url} ${curPageEle} ${curSite.pageUrl}`);
  289. if(url === '') return;
  290. if(curSite.pageUrl === url) return;// 不会重复加载相同的页面
  291. curSite.pageUrl = url;
  292. // 读取下一页的数据
  293. curSite.pager.startFilter && curSite.pager.startFilter();
  294. GM_xmlhttpRequest({
  295. url: url,
  296. method: "GET",
  297. timeout: 5000,
  298. onload: function (response) {
  299. try {
  300. var newBody = ShowPager.createDocumentByString(response.responseText);
  301. let pageElems = getAllElements(curSite.pager.pageElement, newBody, newBody);
  302. let toElement = getAllElements(curSite.pager.HT_insert[0])[0];
  303. if (pageElems.length >= 0) {
  304. let addTo = "beforeend";
  305. if (curSite.pager.HT_insert[1] == 1) addTo = "beforebegin";
  306. // 插入新页面元素
  307. pageElems.forEach(function (one) {
  308. toElement.insertAdjacentElement(addTo, one);
  309. });
  310. // 替换待替换元素
  311. try {
  312. let oriE = getAllElements(curSite.pager.replaceE);
  313. let repE = getAllElements(curSite.pager.replaceE, newBody, newBody);
  314. if (oriE.length === repE.length) {
  315. for (var i = 0; i < oriE.length; i++) {
  316. oriE[i].outerHTML = repE[i].outerHTML;
  317. }
  318. }
  319. } catch (e) {
  320. console.log(e);
  321. }
  322. }
  323. } catch (e) {
  324. console.log(e);
  325. }
  326. }
  327. });
  328. }
  329. },
  330. };
  331.  
  332.  
  333. function getElementByXpath(e, t, r) {
  334. r = r || document, t = t || r;
  335. try {
  336. return r.evaluate(e, t, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
  337. } catch (t) {
  338. return void console.error("无效的xpath");
  339. }
  340. }
  341.  
  342.  
  343. function getAllElements(e, t, r, n, o) {
  344. let getAllElementsByXpath = function(e, t, r) {
  345. return r = r || document, t = t || r, r.evaluate(e, t, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  346. }
  347.  
  348. var i, s = [];
  349. if (!e) return s;
  350. if (r = r || document, n = n || window, o = o || void 0, t = t || r, "string" == typeof e) i = 0 === e.search(/^css;/i) ? function getAllElementsByCSS(e, t) {
  351. return (t || document).querySelectorAll(e);
  352. }(e.slice(4), t) : getAllElementsByXpath(e, t, r); else {
  353. if (!(i = e(r, n, o))) return s;
  354. if (i.nodeType) return s[0] = i, s;
  355. }
  356. return function makeArray(e) {
  357. var t, r, n, o = [];
  358. if (e.pop) {
  359. for (t = 0, r = e.length; t < r; t++) (n = e[t]) && (n.nodeType ? o.push(n) : o = o.concat(makeArray(n)));
  360. return a()(o);
  361. }
  362. if (e.item) {
  363. for (t = e.length; t;) o[--t] = e[t];
  364. return o;
  365. }
  366. if (e.iterateNext) {
  367. for (t = e.snapshotLength; t;) o[--t] = e.snapshotItem(t);
  368. return o;
  369. }
  370. }(i);
  371. }
  372. })();