tags:

views:

58

answers:

4

Hi,

how to write a program/script that will click a button on a web page? The button's function is:OnClick="func();". Firebug gives no information about the called function, so I can't call an AJAX query.

:)

A: 

You can't do this with JavaScript, without dumping the contents of the page on your page or using an iframe. And, you can't interact with elements inside iframes from outside of it (unless it is on the same domain; thanks @Pekka)

SimpleCoder
I did not know that. Thanks :) You learn something new everyday.
SimpleCoder
@Simple this is a good article on the issue: https://developer.mozilla.org/En/Same_origin_policy_for_JavaScript
Pekka
I knew about the same-origin policy, but didn't know that it applied to `iframes`.
SimpleCoder
+1  A: 

There is click method for Input and Anchor element.

DoubleThink
A: 

You can't do that unless you control the server of web page to some extent (in which case you can use cross-domain AJAX or something equivalent), but you might be able to replicate the effect of clicking the button. This is known as a CSRF attack.

Tgr
A: 

Let's say you have button A. When button A is pressed, function X is supposed to run. You could use the click method as DoubleThink suggested, or you could just directly run function X.

option 1 = document.getElementById('A').click()

option 2 = X()

Note: many people suggest doing this: document.getElementById('A').onclick(), but there are multiple ways to bind functions to events and this way does not cover all those ways -- it only covers the case where someone had <button onclick="..."/>. For Example, if you use jQuery, using .onclick will not suffice.

Thr4wn