Clicking a link with greasemonkey from the content inside link

时光怂恿深爱的人放手 提交于 2019-12-23 23:37:23

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/6379507/clicking-a-link-with-greasemonkey-from-the-content-inside-link

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