user736577
user736577

Reputation: 11

Watir: How do I execute a JS function which is called through onload through an iframe?

The goal is to have Watir click a button that functions purely through JS.

The main page has an iframe that looks similar to this:

<iframe name="uploadfile" id="uploadfile" src="form1.html" frameBorder="0" scrolling="no" height="0" width="100%"></iframe>

form1.html calls a JS function with onload within the body similar to:

<body onload="submit();" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0" class="formx">

Which then presents a button to me with a value/id I can use. I just can't figure out how to click that button through the iframe and onload.

I've tried using frame() and fire_event() and sourcing it directly without success. I'm new to Watir and ruby so perhaps their is an easier way to do this?

Upvotes: 1

Views: 1304

Answers (3)

Chuck van der Linden
Chuck van der Linden

Reputation: 6660

To accommodate the onload, you might need to have you script sleep for a second or so in order to give the client side code time to do it's thing. That or use some of the techniques described on the How to Wait With Watir page to wait for the button to exist.

You should not need to fire the 'onload' event as far as I know the browser itself would do that as it loads the HTML for the frame, the only detail would be providing enough time for the client side code to have done its thing before trying to make use of any elements that are created by that code.

Otherwise the only 'trick' to addressing the button would be to properly locate and identify it within the DOM. If the button is created inside the iframe, then as indicated in Zeljko's response you will need to use something along the lines of

browser.frame(:id => "uploadfile").button(:id => "click_me").click

I recommend using IRB as the way to develop your scripts since you can test out individual commands one at a time and see what works. it's a lot like being able to step through stuff in a debugger, just a tiny bit more manual.

Upvotes: 1

Željko Filipin
Željko Filipin

Reputation: 57262

Watir does not care if the button is created by JavaScript or not. If it is displayed on the page, it can click it.

Use Firebug (or similar tool) to inspect the button, it should look like similar to this:

<input type="button" id="click_me">

or this:

<button id="click_me">

and you can click it with:

browser.button(:id => "click_me").click

Since the button is in frame, you have to specify it:

browser.frame(:id => "uploadfile").button(:id => "click_me").click

Upvotes: 1

Gabriel
Gabriel

Reputation: 1833

You want to access the main window from the iframe? If so, try using the top object in JavaScript.

top.document.getElementById("your_button").doSomething()

Upvotes: 0

Related Questions