Click a link with Javascript when there is no element ID

只愿长相守 提交于 2019-12-01 07:52:37

问题


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.

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?


回答1:


var link = document.querySelector('[href*="/cgi/admin/user/ssh_login/"]');
link.click();

Edit:

Open link in a background tab in chrome (based on this answer)

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);
}



回答2:


If the content of the anchor is always going to be 'SSH' you can use;

$("a:contains('SSH')")



来源:https://stackoverflow.com/questions/32952686/click-a-link-with-javascript-when-there-is-no-element-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!