简体   繁体   English

如何使用GreaseMonkey中的javascript模拟具有特定文本的锚点单击?

[英]How to simulate click on anchor with specific text using javascript in GreaseMonkey?

Suppose I load a webpage which contains the following anchor: 假设我加载了一个包含以下锚点的网页:

<a class="someClass" href="#" onClick="gotoPage('http://somepage.org')">Link</a>

What I want is: as soon as the page is loaded, I want to generate onClick for this anchor which has text as "Link". 我想要的是:页面加载后,我想为此锚(其文本为“链接”)生成onClick。

Note that the anchor does not contains any id or name associated with it. 请注意,锚点不包含任何与之关联的ID或名称。 Thus document.getelementbyid or document.getelementbyname will not work. 因此,document.getelementbyid或document.getelementbyname将不起作用。

Here is what people seem to do to be able to generically trigger a click event in Firefox. 人们似乎 可以这样做 ,从而能够在Firefox中普遍触发click事件。 They extend the HTMLAnchorElement prototype with a click() function, like so: 他们使用click()函数扩展了HTMLAnchorElement原型,如下所示:

HTMLAnchorElement.prototype.click = function() {
  var evt = this.ownerDocument.createEvent('MouseEvents');
  evt.initMouseEvent('click', true, true, this.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
  this.dispatchEvent(evt);
}

See MDC for initMouseEvent() . 有关initMouseEvent()请参见MDC

If you have jQuery, you might also check out trigger() . 如果您使用jQuery,则还可以签出trigger()

As you're using Greasemonkey you should be able to use XPath to select the link in question using one of it's HTML attributes: 使用Greasemonkey时,您应该能够使用XPath使用其中的HTML属性之一来选择相关链接:

http://diveintogreasemonkey.org/patterns/match-attribute.html http://diveintogreasemonkey.org/patterns/match-attribute.html

The solution (which Tomalak linked to) from https://developer.mozilla.org/en/DOM/event.initMouseEvent worked great for me, and it doesn't require prototype or jquery. 来自https://developer.mozilla.org/en/DOM/event.initMouseEvent的解决方案(Tomalak链接到该解决方案)对我来说非常有效,并且不需要原型或jquery。

function simulateClick() {
  var evt = document.createEvent("MouseEvents");
  evt.initMouseEvent("click", true, true, window,
    0, 0, 0, 0, 0, false, false, false, false, 0, null);
  var cb = document.getElementById("checkbox"); 
  var canceled = !cb.dispatchEvent(evt);
  if(canceled) {
    // A handler called preventDefault
    alert("canceled");
  } else {
    // None of the handlers called preventDefault
    alert("not canceled");
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM