Way to Open Clicked Link in New Tab via Tampermonkey?

梦想的初衷 提交于 2021-02-08 13:45:26

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/51682166/way-to-open-clicked-link-in-new-tab-via-tampermonkey

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