When you use Greasemonkey to click a link embedded within the content

In need of assistance with clicking a dynamic link using Greasemonkey. The only static part of the code is the text 'Attack This Player'. The href attribute of the link changes depending on the page.

Here is my current code:

function click_element(element)
{
    var event = document.createEvent("MouseEvents");
    event.initMouseEvent("click", true, true, document.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
    element.dispatchEvent(event);
    return;
};

click_element( document.evaluate("//a[I DON'T KNOW WHAT TO PUT HERE]",document,null,9,null).singleNodeValue );

This code works for links with ids, classes, etc.

Any help on this matter would be greatly appreciated as my JavaScript skills are not very advanced.

Thanks,

Reblerebel

Answer №1

Instead of relying on XPath, it is recommended to use jQuery for a simpler solution.

If simply clicking on the link redirects you to the desired page, the script can be as straightforward as:

// ==UserScript==
// @name            Attack!
// @include         http://YOUR_SITE/YOUR_PATH/*
// @require         http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js
// ==/UserScript==

//--- contains is case-sensitive.
var attackLink          = $("a:contains('Attack This Player')");

//--- Easily "click" the link.
window.location.href    = attackLink[0].href;


Alternatively, if the link's action is controlled by the page's JavaScript (although this seems unlikely based on the provided example link):

// ==UserScript==
// @name            Attack!
// @include         http://YOUR_SITE/YOUR_PATH/*
// @require         http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js
// ==/UserScript==

//--- contains is case-sensitive.
var attackLink          = $("a:contains('Attack This Player')");

//--- Simulate a click event if the link's action was overridden by JavaScript.
var evt                 = document.createEvent ("HTMLEvents");
evt.initEvent ("click", true, true);
attackLink[0].dispatchEvent (evt);

Update for comment(s):

Are there multiple links or do they always begin with "/attack/index/"?

If that's the case, you can use:

var attackLink          = $("a[href^='/attack/index/']");

If the situation is more complex, it is advisable to ask a separate question providing detailed information about the target pages' code. Including links to the pages would be helpful.

Selecting elements on a target page is a nuanced process that is highly dependent on the specific page.
jQuery simplifies this process with CSS-like selection; here is a useful jQuery selector reference.

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

Using Input Mask with TextField Component in Material-UI with React Hook Form

Currently, I am trying to utilize the MUI's TextInput component alongside the MaskInput component from react-input-mask and react-hook-form. Despite everything appearing to be functioning correctly, an error message related to using refs keeps popping ...

Is there a way to eliminate text from a barcode image using JavaScript or TypeScript?

This is my unique html code <div class="pr-2" style="width: 130px"> <div *ngIf="!element.editing" > <span class="ss">{{element.barcode}}</span> </di ...

While the NPM package functions properly when used locally, it does not seem to work when installed from the

I have recently developed a command-line node application and uploaded it to npm. When I execute the package locally using: npm run build which essentially runs rm -rf lib && tsc -b and then npm link npx my-package arguments everything works sm ...

Divide the string into segments and set up pagination

<div><p class="pagi">page 1 content</p><p class="pagi">page 2 content</p><p class="pagi">page 3 content</p></div> I am currently facing a challenge with the string provided above. I need to create pagination ...

Are there any risks associated with using nested setTimeout functions with the same name?

While reviewing the source code of typed.js, I noticed that the main function in this plugin utilizes a design pattern with multiple setTimeout functions nested inside one another. Here is a snippet of the code: self.timeout = setTimeout(function() { / ...

Is it possible to substitute the variables with the function name?

Is there a way to duplicate the variable name? Take a look at the example below (note the name a1) $(document).ready(function() { name = "a1"; // This is "NAME" as a1 }) function name() { // USING "NAME" $("#test" + name).keydown(function(a) ...

What is the correct way to retrieve a JSON object instead of getting [Object object]?

Creating a basic web scraper integrated with mongoDB. Even though the API returns the JSON object in the correct format, when trying to append it to a bootstrap card on the page, I'm getting [Object object]. Below is my JavaScript code running on th ...

Sharing tips for sending error objects to a socket.io callback

Utilizing callbacks with socket.io Client side code : socket.emit('someEvent', {data:1}, function(err, result) { console.log(err.message); }); Server side code : socket.on('someEvent', function(data, callback) { callback(ne ...

Exclude the file and directory patterns from being watched with PM2: ignore folder

I need help with configuring pm2 to stop monitoring folders that have names like cache or tmp. I've tried multiple approaches in my app.json configuration file: {"apps": [{ "name": "BSTAT", "script": &q ...

Incorporate Angular frontend into current website or project

I've successfully built a website using bootstrap, but now I'm looking to integrate Angular in order to transform it into a single page application. The goal is that when a user clicks on a link, only the necessary content will be loaded from the ...

Can I construct an html table-esque layout employing fabric js?

https://i.stack.imgur.com/Zwkj3.jpg I'm in the process of developing a schema builder inspired by vertabelo. To achieve this, I've opted to utilize fabric.js for its interactive features. My main challenge lies in creating an HTML table-like str ...

Display a pop-up upon clicking a button

I've created a custom popup form using Flodesk and added the corresponding Javascript Snippet to my website just before the closing head tag. <script> (function(w, d, t, h, s, n) { w.FlodeskObject = n; var fn = function() { (w[n] ...

Assigning a JavaScript code block to execute exclusively on designated pages

I have implemented webpack to bundle all my .js files into one app.js, which is utilized across all pages in my project. However, I have encountered an issue where code intended for one page is impacting another page where it is not required. For example, ...

Ways to modify the color of a container's border by interacting with radio buttons through JavaScript

I'm currently facing a challenge with creating a settings dropdown menu that allows users to select different themes. Each theme is supposed to modify the background color and border color, but I have successfully implemented only the background color ...

Tips on invoking a function from an array in JavaScript when a button is clicked

Being new to JavaScript, I encountered a challenge where I have an array of functions: allFunctions = () => [ function1(), function2(), function3(), function4(), function5(), function6(), function7(), function8(), function9() ] My go ...

I currently have a set of 6 popovers that all open simultaneously, but I am looking to make them open sequentially, one after

My component generates a div with 6 different experiences, each with its own popover. However, when I click on an experience to open its popover, all 6 popovers appear. How can I assign a unique ID to each popover? This is the code for my experience compo ...

I have always wondered about the meaning of " + i + " in Javascript. Can you explain it to

<script> var x,xmlhttp,xmlDoc xmlhttp = new XMLHttpRequest(); xmlhttp.open("GET", "cd_catalog.xml", false); xmlhttp.send(); xmlDoc = xmlhttp.responseXML; x = xmlDoc.getElementsByTagName("CD"); table="<tr><th>Artist</th><th>Ti ...

Execute a task on Mobile Safari (after a delay)

I'm currently experimenting with HTML5 on Mobile Safari for iOS 6 and I'm curious about executing JavaScript code after a certain amount of time has elapsed. One specific task I am interested in is redirecting to a different page after 60 seconds ...

Creating a custom HTML5 canvas with images from a JSON array

I am currently working on a project to develop a unique slideshow feature by hosting images in an external JSON array and then loading them onto an HTML page. The next step is to insert these images onto an HTML5 canvas. While I have successfully loaded a ...

Oops! Issue: The mat-form-field is missing a MatFormFieldControl when referencing the API guide

I included the MatFormFieldModule in my code like so: import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppRoutingModule } from './app-routing.module'; ...