Is there a way to use grease/tampermonkey to automatically redirect the current definition from Dictionary.com to Thesaurus.com?

Is there a way to use Greasemonkey or Tampermonkey to automatically open the definition on Dictionary.com at Thesaurus.com, and vice versa, when clicking specific links? (Shown in red)

My initial thought is to retrieve the word being searched from the URL using window.location.pathname, and then place it in the hostname of the opposite link.

The Thesaurus.com link HTML:

<a href="http://www.thesaurus.com/" data-linkid="qxnxzj">Thesaurus.com</a>

The Dictionary.com link HTML:

<a href="http://www.dictionary.com/" data-linkid="tqks0v">Dictionary.com</a>

I considered using either

document.querySelectorAll("a[href='http://www.thesaurus.com']");
or
document.querySelectorAll('[data-linkid=qxnxzj]');
to select the links.

However, I am unsure about relying on the data-linked attribute if it gets changed by the web developer.

As for the implementation, should I listen for all clicks on the document, or just on <a> tags? What would be the most efficient approach?


Additionally, is there a way to make these links open in a new tab when ctrl+clicked, or in a new window when shift+clicked? Currently, they both open in the same browser tab.

Answer №1

The following code successfully fulfilled all the objectives mentioned in my question:

// ==UserScript==
// @name         Modify link behavior on Thesaurus.com
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  attempt to conquer the universe!
// @author       You
// @match        *://www.thesaurus.com/*
// @match        *://www.dictionary.com/*
// @run-at       document-end
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    document.querySelectorAll('[data-linkid]').forEach(el => el.removeAttribute('data-linkid'));

    document.addEventListener('click', function(e) {
        var link = e.target.closest('a');
        //var link = e.target.closest('#content a'); // limit to the #content area
        var path = window.location.pathname; // /browse/myword

        if (link && link.getAttribute('href') != '#') {
            e.stopPropagation();
        }

        if (link && link.getAttribute('href') == 'http://www.thesaurus.com/') {
            link.setAttribute('href', 'http://www.thesaurus.com' + path);
        }
        else if (link && link.getAttribute('href') == 'http://www.dictionary.com/') {
            link.setAttribute('href', 'http://www.dictionary.com' + path);
        }
    }, true);

})();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What's the best way to switch between colors in a Vue list?

I have a custom tree-view component that I'm working on: <template> <li class="main__li list" :style="{'margin-left': `${depth * 20}px` ,'background-color': `${col}`}" @click="toggle(e); getEl( ...

using a function as an argument in the map method within a React component

I have a challenge where I am trying to display blog posts retrieved from my database. However, for each item, I also need to execute a download image function. I attempted to include the function within the .map function but encountered some errors. I am ...

Tips for preventing the browser from freezing when incorporating a large HTML chunk retrieved through AJAX requests

I've developed a web application that showcases information about various items. Initially, only a small portion of the items are displayed at the top level. Upon loading the page for the first time and displaying these initial items, I make an AJAX r ...

Incorporating live text into a tag while arranging items by price in both ascending and descending order

I recently added a button to my online shop that allows users to sort products by price, even though I don't fully understand the underlying JavaScript code. I want to enhance this button by updating the text to indicate whether the sorting order is ...

Utilize Angular 8 to dynamically populate Input values with data pulled from an API

I need help with setting the input value dynamically using data from my API. Once I click send, I want it to be saved in the database. However, I am struggling to dynamically populate the input field. Can someone guide me on the right approach to achieve t ...

Error encountered while parsing Japanese characters using the express body-parser resulting in a bad control character issue

Currently, I am sending a large JSON string to a node express endpoint that is set up like this: import bodyParser from 'body-parser'; const app = express(); const jsonParser = bodyParser.json({ limit: '4mb' }); const databaseUri = &ap ...

403 Error Code - Access Denied when trying to access Cowin Setu APIs

While attempting to create a covid vaccine alert using the Cowin Setu API (India) in nodejs, I encountered a strange issue. Every time I send a get request, I receive a 403 response code from cloudfront stating 'Request Blocked', although it work ...

creating a while loop in node.js

In C#, the following code would be used: double progress = 0; while (progress < 100) { var result = await PerformAsync(); progress = result.Progress; await Task.Delay(); } This concise piece of code spans just 7 lines. Now, how can we ...

insert a gap between two elements in the identical line

Is there a way to create spacing between two text fields in the same row? I have tried using margins, paddings, and display flex in the css file but haven't been successful. import "./styles.css"; import TextField from "@material-ui/cor ...

Unable to modify the selector to "Remove preview files" on click in PHP and JavaScript

During the process of uploading multiple files (using <input type="file" multiple/>) with preview image file and successfully removing the image preview and file data, I encountered a problem. The issue arises when attempting to change the selector ...

javascript: verify the presence of uppercase and lowercase letters

Can the validation of at least 2 lowercase and 2 uppercase letters be implemented when checking the case? Below is the condition I am currently using. function HasMixedCase(passwd){ if(passwd.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)) return true ...

Tips on sending filter parameters from AngularJS to Spring RestController using @MatrixVariable

I’m struggling to figure out how to use $http.get in AngularJS to pass filter parameters. The URL is: http://localhost:8080/template/users/query;username=abcd;firstName=ding... The RestController looks like this: @RequestMapping(value={"/users/{query ...

What is the method for setting a function as the initial value of a state variable?

Here is a function I have: async function setAllValues(value) { await stableSort(rows, getComparator(order, orderBy)) .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage) .forEach((row) => { temp = ...

Is it possible to add a tooltip to a div without using any JavaScript or JQuery?

I've been working on designing a form that includes tooltips displayed constantly on the right side to assist users in completing their forms. To achieve this, I have separated each part into Divs and added a tooltip for each one. <div title="This ...

Is it possible to trigger the setState() function of a parent component when a child component is clicked?

Hey there, I'm a new developer diving into the world of Reactjs. I've been working on setting up a Todo app but struggling to configure it just right. My main challenge is getting a button to add items to the list when submitted. I think I'm ...

The antithesis of jQuery's .parents() selector

I am currently developing a userscript for a webpage with an old-fashioned design consisting mainly of tables. My goal is to access a long table of fields so that they can be filled in automatically by the script. To simplify, the structure is as follows: ...

How can I retrieve the value of $_POST[] immediately after a selection is made in a dropdown box

Is there a way to retrieve the $_POST value immediately after changing the select option without having to submit the form? <select name="cat_id" class="form-control" onChange="this.form.submit();" style="width:300px;"> <?php ...

The dot notation in JSON syntax allows for easy access

Recently, I've been struggling with referencing a variable in JSON dot notation within my meteor application. It seems that when trying to access respJson.userlower.name, userlower is not being recognized as a valid variable. Is there a workaround for ...

Using HTTPS, you can access Flask from AJAX

I have encountered numerous inquiries concerning this issue, but none have proven effective for me. I recently switched my domain from HTTP to HTTPS. Everything was functioning properly on HTTP. The main issue lies in the fact that my javascript and flask ...

I would like to check if a given username and password exist in my JSON data

Trying different methods but not achieving the desired outcome. I have limited knowledge about JSON, gathered some information from online sources. var loginDataList = [{ "username": "abc", "password": "abc123" }, { "username": "richa", "p ...