admin管理员组文章数量:1434916
Suppose I load a webpage which contains the following anchor:
<a class="someClass" href="#" onClick="gotoPage('')">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".
Note that the anchor does not contains any id or name associated with it. Thus document.getelementbyid or document.getelementbyname will not work.
Suppose I load a webpage which contains the following anchor:
<a class="someClass" href="#" onClick="gotoPage('http://somepage')">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".
Note that the anchor does not contains any id or name associated with it. Thus document.getelementbyid or document.getelementbyname will not work.
Share Improve this question edited Jun 11, 2012 at 6:24 TazGPL 3,7462 gold badges41 silver badges60 bronze badges asked Aug 7, 2009 at 11:19 nullDevnullDev 11.6k8 gold badges37 silver badges53 bronze badges3 Answers
Reset to default 3Here is what people seem to do to be able to generically trigger a click
event in Firefox. They extend the HTMLAnchorElement
prototype with a click()
function, like so:
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()
.
If you have jQuery, you might also check out 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:
http://diveintogreasemonkey/patterns/match-attribute.html
The solution (which Tomalak linked to) from https://developer.mozilla/en/DOM/event.initMouseEvent worked great for me, and it doesn't require prototype or 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");
}
}
本文标签: How to simulate click on anchor with specific text using javascript in GreaseMonkeyStack Overflow
版权声明:本文标题:How to simulate click on anchor with specific text using javascript in GreaseMonkey? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745626503a2667004.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论