3
// ==/UserScript==

//--- Note that the contains() text is case-sensitive.
var TargetLink          = $("a:contains('We love potatoes')")

if (TargetLink  &&  TargetLink.length) 
    window.location.href   = TargetLink[0].href

I want to have the links it finds open in a new tab in chrome. This may be obvious to some but I can't figure it for the life of me, can someone assist me?

Victor Zakharov
  • 25,801
  • 18
  • 85
  • 151
  • possible duplicate of [Open url in new tab using javascript](http://stackoverflow.com/questions/4907843/open-url-in-new-tab-using-javascript) – JJJ Mar 30 '13 at 10:26
  • Should it open all links in new windows when this code is run, or do you want the code to alter the DOM, so that the anchors open in new windows when clicked? – Christofer Eliasson Mar 30 '13 at 10:36
  • I'd want all the links to open in the same window but in new tabs. – Tyler Weatherwax Mar 30 '13 at 10:39

3 Answers3

2

Instead of changing the location of the current window, you could use something like window.open() to open a new window instead:

window.open(TargetLink[0].href, "myWindow");

Notice that popup-blockers etc. may prevent the window from being opened.

Side note:

MDN offer a quite extensive read on the use of this, and the general opinion is to avoid resorting to window.open(), for the purpose of usability. Most modern browsers use tabbed browsing, and opening up pages in new windows takes a step away from that.

Christofer Eliasson
  • 32,939
  • 7
  • 74
  • 103
  • I'm still having an issue getting this working. would you mind posting the full code? Maybe I'm being stupid and doing something wrong. Also if it helps I sit in a chat room and want the imgur links to auto open in new tabs. – Tyler Weatherwax Mar 30 '13 at 22:35
1

Use the following code:

var TargetLink = $("a:contains('We love potatoes')"); // this will select your node

if (TargetLink  &&  TargetLink.length) { //checks it node was there
    alert("Going to redirect"); //Just to make sure that we did correct!

    TargetLink.attr('taget', '_blank'); //add target="_blank"
    //TargetLink.click(); // This is not working, because of a security issue.

}

And also notice about ;.

Mostafa Shahverdy
  • 2,687
  • 2
  • 30
  • 51
0

You don't need if checks, just use attr method:

$("a:contains('We love potatoes')").attr('target', '_blank');

So target="_blank" will be added to We love potatoes-links.

Demo: http://jsfiddle.net/qtsWs/

dfsq
  • 191,768
  • 25
  • 236
  • 258