V2EX 增强

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

当前为 2021-12-02 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name V2EX 增强
  3. // @version 1.1.4
  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. document.querySelectorAll('form').forEach(function (_this) {
  324. if (!_this.target) {
  325. _this.target = '_self'
  326. }
  327. });
  328.  
  329. const callback = (mutationsList, observer) => {
  330. for (const mutation of mutationsList) {
  331. for (const target of mutation.addedNodes) {
  332. if (target.nodeType != 1) return
  333. if (target.tagName === 'A') {
  334. if (target.onclick || target.href.slice(0,4) != 'http' || target.href.indexOf('#;') > -1 || target.href.indexOf('night/toggle') > -1 || target.href.indexOf('/favorite') > -1) {
  335. target.target = '_self'
  336. }
  337. } else {
  338. document.querySelectorAll('a').forEach(function (_this) {
  339. if (_this.onclick || _this.href.slice(0,4) != 'http' || _this.href.indexOf('#;') > -1 || _this.href.indexOf('night/toggle') > -1 || _this.href.indexOf('/favorite') > -1) {
  340. _this.target = '_self'
  341. }
  342. });
  343. }
  344. }
  345. }
  346. };
  347. const observer = new MutationObserver(callback);
  348. observer.observe(document, { childList: true, subtree: true });
  349. }
  350.  
  351.  
  352. // 添加全站最近更新主题链接
  353. function addChangesLink() {
  354. let links = document.querySelector('#Main .box .inner:last-child');if (!links) return
  355. 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>`
  356. }
  357.  
  358.  
  359. // 自动无缝翻页
  360. function pageLoading() {
  361. if (curSite.SiteTypeID > 0){
  362. windowScroll(function (direction, e) {
  363. if (direction === 'down') { // 下滑才准备翻页
  364. let scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
  365. //console.log(document.documentElement.scrollHeight)
  366. let scrollDelta = curSite.pager.scrollDelta;
  367. if (document.documentElement.scrollHeight <= document.documentElement.clientHeight + scrollTop + scrollDelta) {
  368. if (curSite.pager.type === 1) {
  369. ShowPager.loadMorePage();
  370. }else{
  371. let autopbn = document.querySelector(curSite.pager.nextLink);
  372. if (autopbn){
  373. autopbn.click();
  374. }
  375. }
  376. }
  377. }
  378. });
  379. }
  380. }
  381.  
  382.  
  383. // 滚动条事件
  384. function windowScroll(fn1) {
  385. var beforeScrollTop = document.documentElement.scrollTop,
  386. fn = fn1 || function () {};
  387. setTimeout(function () { // 延时执行,避免刚载入到页面就触发翻页事件
  388. window.addEventListener('scroll', function (e) {
  389. var afterScrollTop = document.documentElement.scrollTop,
  390. delta = afterScrollTop - beforeScrollTop;
  391. if (delta == 0) return false;
  392. fn(delta > 0 ? 'down' : 'up', e);
  393. beforeScrollTop = afterScrollTop;
  394. }, false);
  395. }, 1000)
  396. }
  397.  
  398.  
  399. // 修改自 https://greasyfork.org/scripts/14178 , https://github.com/machsix/Super-preloader
  400. var ShowPager = {
  401. getFullHref: function (e) {
  402. if (e != null && e.nodeType === 1 && e.href && e.href.slice(0,4) === 'http') return e.href;
  403. return '';
  404. },
  405. createDocumentByString: function (e) {
  406. if (e) {
  407. if ('HTML' !== document.documentElement.nodeName) return (new DOMParser).parseFromString(e, 'application/xhtml+xml');
  408. var t;
  409. try { t = (new DOMParser).parseFromString(e, 'text/html');} catch (e) {}
  410. if (t) return t;
  411. if (document.implementation.createHTMLDocument) {
  412. t = document.implementation.createHTMLDocument('ADocument');
  413. } else {
  414. 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) {}
  415. }
  416. if (t) {
  417. var r = document.createRange(),
  418. n = r.createContextualFragment(e);
  419. r.selectNodeContents(document.body);
  420. t.body.appendChild(n);
  421. 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);
  422. return t;
  423. }
  424. } else console.error('没有找到要转成 DOM 的字符串');
  425. },
  426. loadMorePage: function () {
  427. if (curSite.pager) {
  428. let curPageEle = getElementByXpath(curSite.pager.nextLink);
  429. var url = this.getFullHref(curPageEle);
  430. console.log(`${url} ${curPageEle} ${curSite.pageUrl}`);
  431. if(url === '') return;
  432. if(curSite.pageUrl === url) return;// 不会重复加载相同的页面
  433. curSite.pageUrl = url;
  434. // 读取下一页的数据
  435. curSite.pager.startFilter && curSite.pager.startFilter();
  436. GM_xmlhttpRequest({
  437. url: url,
  438. method: "GET",
  439. timeout: 5000,
  440. onload: function (response) {
  441. try {
  442. var newBody = ShowPager.createDocumentByString(response.responseText);
  443. let pageElems = getAllElements(curSite.pager.pageElement, newBody, newBody);
  444. let toElement = getAllElements(curSite.pager.HT_insert[0])[0];
  445. if (pageElems.length >= 0) {
  446. // 如果有插入前函数就执行函数
  447. if (curSite.function && curSite.function.before) {
  448. if (curSite.function.parameter) { // 如果指定了参数
  449. pageElems = curSite.function.before(curSite.function.parameter);
  450. }else{
  451. pageElems = curSite.function.before(pageElems);
  452. }
  453. }
  454. // 插入位置
  455. let addTo;
  456. switch (curSite.pager.HT_insert[1]) {
  457. case 1:
  458. addTo = "beforebegin"
  459. break;
  460. case 2:
  461. addTo = "afterbegin"
  462. break;
  463. case 3:
  464. addTo = "beforeend"
  465. break;
  466. case 4:
  467. addTo = "afterend"
  468. break;
  469. }
  470. // 插入新页面元素
  471. pageElems.forEach(function (one) {
  472. toElement.insertAdjacentElement(addTo, one);
  473. });
  474. // 替换待替换元素
  475. try {
  476. let oriE = getAllElements(curSite.pager.replaceE);
  477. let repE = getAllElements(curSite.pager.replaceE, newBody, newBody);
  478. if (oriE.length === repE.length) {
  479. for (var i = 0; i < oriE.length; i++) {
  480. oriE[i].outerHTML = repE[i].outerHTML;
  481. }
  482. }
  483. } catch (e) {
  484. console.log(e);
  485. }
  486. // 如果有插入后函数就执行函数
  487. if (curSite.function && curSite.function.after) {
  488. if (curSite.function.parameter) { // 如果指定了参数
  489. curSite.function.after(curSite.function.parameter);
  490. }else{
  491. curSite.function.after();
  492. }
  493. }
  494. }
  495. } catch (e) {
  496. console.log(e);
  497. }
  498. }
  499. });
  500. }
  501. },
  502. };
  503. function getElementByCSS(css, contextNode = document) {
  504. return contextNode.querySelector(css);
  505. }
  506. function getAllElementsByCSS(css, contextNode = document) {
  507. return [].slice.call(contextNode.querySelectorAll(css));
  508. }
  509. function getElementByXpath(xpath, contextNode, doc = document) {
  510. contextNode = contextNode || doc;
  511. try {
  512. const result = doc.evaluate(xpath, contextNode, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
  513. // 应该总是返回一个元素节点
  514. return result.singleNodeValue && result.singleNodeValue.nodeType === 1 && result.singleNodeValue;
  515. } catch (err) {
  516. throw new Error(`Invalid xpath: ${xpath}`);
  517. }
  518. }
  519. function getAllElementsByXpath(xpath, contextNode, doc = document) {
  520. contextNode = contextNode || doc;
  521. const result = [];
  522. try {
  523. const query = doc.evaluate(xpath, contextNode, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  524. for (let i = 0; i < query.snapshotLength; i++) {
  525. const node = query.snapshotItem(i);
  526. // 如果是 Element 节点
  527. if (node.nodeType === 1) result.push(node);
  528. }
  529. } catch (err) {
  530. throw new Error(`无效 Xpath: ${xpath}`);
  531. }
  532. return result;
  533. }
  534. function getAllElements(selector, contextNode = undefined, doc = document, win = window, _cplink = undefined) {
  535. if (!selector) return [];
  536. contextNode = contextNode || doc;
  537. if (typeof selector === 'string') {
  538. if (selector.search(/^css;/i) === 0) {
  539. return getAllElementsByCSS(selector.slice(4), contextNode);
  540. } else {
  541. return getAllElementsByXpath(selector, contextNode, doc);
  542. }
  543. } else {
  544. const query = selector(doc, win, _cplink);
  545. if (!Array.isArray(query)) {
  546. throw new Error('getAllElements 返回错误类型');
  547. } else {
  548. return query;
  549. }
  550. }
  551. }
  552. })();