3

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?

12
  • What is the surrounding markup? Is it inside a div container with id provided? Commented Oct 5, 2015 at 15:54
  • why cant you give this link an id? <a id="someID" href="/cgi/admin/user/ssh_login/*" target="_blank">SSH</a> Does something prevent you from doing this when you are generating the link? Commented Oct 5, 2015 at 15:54
  • 1
    document.querySelector('a').fireEvent('click') - I have to say that this looks dodgy. Open a tab in the background and auto-click a link? You better not want to use this for evil. Commented Oct 5, 2015 at 15:55
  • 1
    @somethinghere Note they might not want to click every <a> and only a certain one by it's content or href. Commented Oct 5, 2015 at 15:57
  • 1
    I recommend @Brians elegant solution now ;-) Commented Oct 5, 2015 at 16:20

2 Answers 2

8
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);
}
Sign up to request clarification or add additional context in comments.

16 Comments

@Mr_Green .click() fires the click event, not onclick which defines it.
onclick is an inline event listener. click() simulates a mouse click.
another question, why [href*= wouldn't [href^= works here as we know it starts from there only?
@Mr_Green it sure would, *= was just the first one that came to mind.
@MisterPyrrhuloxia window.onload = function(){ /*code*/ }
|
0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.