乐闻世界logo
搜索文章和话题

How to Open Clicked Link in New Tab via Tampermonkey?

1个答案

1

When using the Tampermonkey script manager to enable opening links in new tabs in your browser, first ensure that Tampermonkey is installed. Follow these steps to create and use a simple script for this functionality:

Step 1: Install Tampermonkey

  1. Open your browser (e.g., Chrome).
  2. Visit the Chrome Web Store or the corresponding extension store for your browser.
  3. Search for 'Tampermonkey' and select 'Add to browser'.
  4. After installation, ensure the extension is enabled.

Step 2: Create a New Script

  1. Click the Tampermonkey icon in the top-right corner of the browser.
  2. Select 'Create new script...'.
  3. This will open the Tampermonkey script editor.

Step 3: Write the Script

In the script editor, write a simple script to make all links open in new tabs by default. Here is a basic example:

javascript
// ==UserScript== // @name Open Links in New Tabs // @namespace http://tampermonkey.net/ // @version 0.1 // @description Enable opening links in new tabs. // @author Your Name // @match *://*/* // @grant none // ==/UserScript== (function() { 'use strict'; // Retrieve all link elements on the page var links = document.getElementsByTagName("a"); // Iterate through each link and set its target attribute to "_blank" for (var i = 0; i < links.length; i++) { links[i].target = "_blank"; } })();

Step 4: Save and Test the Script

  1. In the script editor, click the 'File' menu and select 'Save'.
  2. Open any webpage and try clicking links; if they open in new tabs, the script is working correctly.

Example Explanation

In this script, we first use getElementsByTagName to retrieve all <a> elements (i.e., links) on the page. Then, we iterate through these links and set the target attribute of each to _blank, ensuring they open in new browser tabs when clicked.

This is a basic example of how to automatically set links to open in new tabs using Tampermonkey across all webpages without manual code modifications.

2024年6月29日 12:07 回复

你的答案