[greasemonkey-users] Click a link using Javascript and GreaseMonkey

1,306 views
Skip to first unread message

FedeWP

unread,
Mar 1, 2010, 12:16:22 PM3/1/10
to greasemon...@googlegroups.com

Hi everyone,

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

unread,
Mar 1, 2010, 2:09:14 PM3/1/10
to greasemon...@googlegroups.com
Are you getting any messages in the Error Console?
What happens if you insert an alert just before calling fireEvent?

cc | pseudonymous |<http://carlclark.mp/>


Fracture

unread,
Mar 1, 2010, 4:22:45 PM3/1/10
to greasemonkey-users
This code worked for me last time I checked, but it was only intended
for Firefox. It will dispatch a click event on the element your give
it. If it's an anchor element and the event isn't canceled somewhere,
it will follow the link normally. I just pasted this in from a
project of mine. In hindsight, I should have checked and made sure
the anchor element had an href attribute before trying to go to it.

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);

Reply all
Reply to author
Forward
0 new messages