V2EX 增强

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

当前为 2021-10-08 提交的版本,查看 最新版本

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