reblerebel
reblerebel

Reputation: 43

Clicking a link with greasemonkey from the content inside link

i have a link that i need to click using greasemonkey <a href="/attack/index/1016587">Attack This Player</a> that is the code the thing is that the href is changeable depending on the page and the only static code is the text of 'attack this player

i currently have

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 currently works for links with ids, classes e.t.c. (sorry for all caps but its just to draw attention to the area)

thanks for any help i am not that advanced in JavaScript

Reblerebel

Upvotes: 2

Views: 4543

Answers (1)

Brock Adams
Brock Adams

Reputation: 93473

Rather than use XPath, use jQuery -- it will be simpler.

If clicking that link merely takes you to the appropriate page then the whole script could be as simple 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')");

//--- "Click" the link the easy way.
window.location.href    = attackLink[0].href;


Or, if the link action is controlled by the page's JavaScript (doesn't seem likely based on the example link given):

// ==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')");

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

Update for comment(s):

Is there always just one link? Do the links always start with "/attack/index/"?

If so, then you can use:

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

If it's more complicated, open another question and give full details of the target pages' code. Links to the pages are best.

Selecting elements of a target page is an art and highly page specific.
jQuery makes it easier with CSS-type selection; Here's a handy jQuery selector reference.

Upvotes: 6

Related Questions