suchnewuser
suchnewuser

Reputation: 41

downloading files behind javascript button with htmlunit

I am trying to download something an attachment behind a javascript button with HtmlUnit. Performing other tasks works great (eg. navigating, login). I checked out the attachment unit test but it didnt help me.

final WebClient webClient = new WebClient(BrowserVersion.FIREFOX_24);
final HtmlPage page1 = webClient.getPage( loginUrl );
final HtmlTextInput textField =  page1.getElementByName(user);
final HtmlPasswordInput pwd =  page1.getElementByName(pwd);  
textField.setValueAttribute(User.getUsername());
pwd.setValueAttribute(User.getPassword());   

final HtmlSubmitInput button =  page1.getElementByName(login);
final HtmlPage page2 =  button.click();

String buttonJavaScript = "window.location='"+folder+filename + ....... ";
ScriptResult result = page2.executeJavaScript(buttonJavaScript);
webClient.waitForBackgroundJavaScript(2000);    

InputStream is = result.getNewPage().getWebResponse().getContentAsStream();
try {
    File f = new File("filename.extension");
    OutputStream os = new FileOutputStream(f);
    byte[] bytes = new byte[1024];
    while (read == is.read(bytes)) {
        os.write(bytes, 0, read);
    }
    os.close();
    is.close();
} catch (IOException ex) {
    // Exception handling
}

However, it stops with:

runtimeError: message=[No node attached to this object] sourceName=[http://pagead2.googlesyndication.com/pagead/osd.js] line=[7] lineSource=[null] lineOffset=[0]

The file created is size 0. There must be a way to get to the real file attached?!

Thank you in advance

Upvotes: 2

Views: 1195

Answers (1)

suchnewuser
suchnewuser

Reputation: 41

Just in case anyone else is wondering: You need to use the AttachmentHandler.

            ScriptResult result = page2.executeJavaScript(buttonJavaScript);
            webClient.waitForBackgroundJavaScript(1000);

            if( attachments.size() > 0 )
            {
                Attachment attachment = attachments.get(0);

                Page attachedPage = attachment.getPage();
                WebResponse attachmentResponse = attachedPage.getWebResponse();

                String content = attachmentResponse.getContentAsString();

                ... write(content); 
            }

Upvotes: 2

Related Questions