I want to simulate a link click in Firefox using Javascript. Directly
navigating to the address is not enough in my case.
I've been struggling and making research about this for quite a while now,
read many forums and posts.
I try a specific code in a Javascript console and it works, but when I use
the same code on a GreaseMonkey script the link is not clicked.
Here goes the code I'm trying:
link = document.getElementById('link');
alert('link = ' + link);
function fireEvent(obj,evt){
alert('fireEvent');
var fireOnThis = obj;
if( document.createEvent ) {
alert('createEvent');
var evObj = document.createEvent('MouseEvents');
evObj.initEvent( evt, true, false );
fireOnThis.dispatchEvent(evObj);
} else if( document.createEventObject ) {
fireOnThis.fireEvent('on'+evt);
}
}
fireEvent(link, 'click');
The link element is obtained correctly but the alert('fireEvent') never gets
triggered.
Is my approach correct or should I try other way?
Does Firefox somehow prevents clicking a link programatically?
Any help on this would be greatly appreciated.
Thanks in advance.
Regards,
Fede
--
View this message in context: http://old.nabble.com/Click-a-link-using-Javascript-and-GreaseMonkey-tp27746319p27746319.html
Sent from the GreaseMonkey List mailing list archive at Nabble.com.
cc | pseudonymous |<http://carlclark.mp/>
function mouseEvent(parent, type) {
var evt = parent.ownerDocument.createEvent('MouseEvents');
evt.initMouseEvent(type, true, true,
parent.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false,
false, 0, null);
return parent.dispatchEvent(evt);
}
function click(parent) {
return mouseEvent(parent, 'click');
}
function clickLink(target) {
var notCanceled = click(target);
if(target.tagName=="A" && notCanceled) window.location.href =
target.href;
}
To use:
var link = document.getElementById("...");
clickLink(link);