Search code examples
framehtmlunit

How to Deal with HtmlUnit and Frames. Tricky Frame Logic


My original question was confusing, I rewrote it. Now it is much clearer.

Hello I am trying to navigate web page using HtmlUnit. I am trying to go to url -> enter text in text box (in frame 1) -> Press Search Button (in frame 1) -> go to new frame (frame 2) that appeared as result of search.

When I write this code:

HtmlPage page = webClient.getPage("http://someurl.com");

HtmlPage toolbar = (HtmlPage) page.getFrameByName("toolbar").getEnclosedPage(); //GET TOOLBAR FRAME 

HtmlTextInput searchBox = toolbar.getElementByName("query"); //GET TEXT BOX ELEMENT

searchBox.setValueAttribute("SOME STRING"); //FILL TEXT BOX ELEMENT WITH TEXT

List<HtmlElement> elements1 = (List<HtmlElement>) toolbar.getByXPath(<SOME XPATH>); //LIST OF A SINGLE ELEMENT WHICH IS THE SEARCH BUTTON

HtmlElement element2 = elements1.get(0); // GET SEARCH BUTTON ELEMENT FROM LIST

page = element2.click();  // CLICK SEARCH BUTTON AND LOAD NEW PAGE TO "page"

I am searching for "SOME STRING". When I do this, another page comes up (though does not refresh the page, the URL never refreshes) with an ADDITIONAL frame. So now, I click the search button but thew new page is just a webpage of the toolbar frame, not of the whole webpage.

I want to now access the additional frame. So how do I "back out" of the current frame and select the new frame?


Solution

  • I found out the answer my trial and error.

    page = (HtmlPage) searchButton.click().getEnclosingWindow().getTopWindow().getEnclosedPage();
    page = (HtmlPage) page.getFrameByName("Frame 1").getEnclosedPage();
    page = (HtmlPage) page.getFrameByName("Frame 2").getEnclosedPage();
    

    It works great, hope I can help some of you out.