Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Way to Open Clicked Link in New Tab via Tampermonkey?

So I have what seems to be a simple problem. I'm trying to automatically open a specific link on a page using the following code:

// ==UserScript==
// @name     AutoClicker
// @include  https://example.com/*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js
// @grant    GM_addStyle
// ==/UserScript==

var TargetLink = $("a:contains('cars')")

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

//--- but open it in a new tab

Which works splendidly.

The only problem is that I don't know a way to open the selected link in a new tab. I've tried iterations of the following code, but to no avail:

var TargetLink = $("a:contains('cars,' '_blank')")

I know I'll need to use _blank, but I'm not sure exactly where or whether I should write it in jQuery or not. I've also tried placing _blank outside of contains, but I'm not exactly sure how I'd write the code in jQuery.

I simply want the selected link to open in a new tab upon being clicked. Any suggestions or thoughts?

like image 483
theCrabNebula Avatar asked Aug 04 '18 03:08

theCrabNebula


1 Answers

The question is not clear, asking two different things. Do you want the tab to open with no user interaction or not?

If yes, Tampermonkey has a function for that: GM_openInTab()Doc.

So:

// ==UserScript==
// @name     AutoClicker
// @include  https://example.com/*
// @require  https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js
// @grant    GM_openInTab
// ==/UserScript==

var TargetLink = $("a:contains('cars')");

if (TargetLink.length)
    GM_openInTab (TargetLink[0].href);

If not, That's easy too with jQuery's attr()Doc.

So:

// ==UserScript==
// @name     NOT an AutoClicker, per question text
// @include  https://example.com/*
// @require  https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js
// @grant    GM_addStyle
// ==/UserScript==

var TargetLink = $("a:contains('cars')");

if (TargetLink.length)
    TargetLink.attr ('target', '_blank');

For a javascript-driven page (also works on static pages):

// ==UserScript==
// @name     NOT an AutoClicker, per question text
// @match    *://YOUR_SERVER.COM/YOUR_PATH/*
// @require  https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @require  https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant    GM_addStyle
// @grant    GM.getValue
// ==/UserScript==
//- The @grant directives are needed to restore the proper sandbox.

waitForKeyElements ("a:contains('cars')", blankifyLink);

function blankifyLink (jNode) {
    jNode.attr ('target', '_blank');
}
like image 51
Brock Adams Avatar answered Sep 22 '22 16:09

Brock Adams