当没有元素ID时,单击带有Javascript的链接 [英] Click a link with Javascript when there is no element ID
问题描述
请原谅我,如果这已经回答了某个地方,但我只是找不到我要找的。我在Chrome中使用Greasemonkey for Firefox和Tampermonkey来尝试创建一个Javascipt来改变我与网页的交互方式。加载网页后,我想在后台自动打开新标签页中的链接。每次加载页面时,此链接略有不同。网页中的元素为:
Please forgive me if this has already been answered somewhere but I just can't find what I'm looking for. I'm using Greasemonkey for Firefox and Tampermonkey in Chrome to try to create a Javascipt to change how I interact with a webpage. Upon page load, I'd like to automatically open a link in a new tab in the background. This link is slightly different each time I load the page. The element from the webpage is this:
<a href="/cgi/admin/user/ssh_login/*" target="_blank">SSH</a>
带有*的部分每次都不同。
The part with the * is what's different each time.
那么,如果没有elementID或者至少有一个elementName,那么如何在页面加载时自动点击该链接?
So how can I automatically click that link upon page load if it doesn't have an elementID or at the very least an elementName?
推荐答案
var link = document.querySelector('[href*="/cgi/admin/user/ssh_login/"]');
link.click();
编辑:
背景标签(基于此答案)
var link = document.querySelector('[href*="/cgi/admin/user/ssh_login/"]');
var url = link.getAttribute('href');
openNewBackgroundTab(url);
function openNewBackgroundTab(url){
var a = document.createElement("a");
a.href = url;
var evt = document.createEvent("MouseEvents");
//the tenth parameter of initMouseEvent sets ctrl key
evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0,
true, false, false, false, 0, null);
a.dispatchEvent(evt);
}
这篇关于当没有元素ID时,单击带有Javascript的链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!