views:

19

answers:

1

I am using browsermob and selenium for creating scripts to run on a site. I am trying to grab all of the elements on the page with a certain name. My problem is when I try to use window.document.getElementsByName("name"); browsermob says that window is not defined. How do you define window?

+3  A: 

You need to call selenium.getEval(). The signature of that call is that it takes a string argument, which is the JavaScript that will be executed in the browser, and it returns a string, which is the string representation of the returned results.

That last part - the string representation - is important. While you certainly can't do this in your BrowserMob script:

var elements = window.document.getElementsByName("name");

You also can't do this:

var elements = selenium.getEval('return window.document.getElementsByName("name")');

While that second example is closer to what you need to do, it's not quite going to work because getElementsByName returns an array of DOM objects that get converted in to a string. Instead, you most likely need to decide what you want to do with those elements and create a larger JS snippet to eval that returns exactly what you want.

For example, this will return the href attribute of the second link in the page:

var secondHref = selenium.getEval('return window.document.getElementsByName("a")[1].href');

I hope that helps. The main thing you need to understand is that while BrowserMob scripts can be written in JavaScript, that JavaScript environment that it runs in is not in the browser. To evaluate arbitrary JavaScript in the browser, you must go through getEval(), thus creating a bit of a JavaScript-in-JavaScript situation that can get a little confusing.

Patrick Lightbody
Thanks. I figured most of that out after I asked it but I haveselenium.getEval('window.document.getElementsByName("a")[1].href');what does the return do?
chromedude