0

I need small help.

I want to open some page using Java and Selenium or HtmlUnit, and after opening this page execute url like Ajax and get to String the response.

Let say, a want to open http://www.somepage.com , when driver is still on this page, execute GET http://www.somepage.com/myAjax/xyz , which should return JSON.

Then i want to get the JSON response and do something with it.

Could you help me, how to do it ?

Best regards

Ilkar
  • 2,113
  • 9
  • 45
  • 71

1 Answers1

0
  1. To inject your own javascript, you can do something like:
        new WebConnectionWrapper(webClient) {

            public WebResponse getResponse(WebRequest request) throws IOException {
                WebResponse response = super.getResponse(request);
                if (request.getUrl().toExternalForm().contains("my_url")) {
                    String content = response.getContentAsString("UTF-8");

                    // inject the below to the 'content' 

                    String tobeInjected = ""
                            + "<script>\n"
                            + "var myOwnVariable;\n"
                            + "var xmlhttp;\n"
                            + "if (window.XMLHttpRequest) {\n"
                            + "  xmlhttp=new XMLHttpRequest();\n"
                            + "}\n"
                            + "else {\n"
                            + "  xmlhttp=new ActiveXObject('Microsoft.XMLHTTP');\n"
                            + "}\n"
                            + "\n"
                            + "xmlhttp.onreadystatechange=function() {\n"
                            + "  if (xmlhttp.readyState==4 && xmlhttp.status==200) {\n"
                            + "    myOwnVariable = xmlhttp.responseText;\n"
                            + "  }\n"
                            + "}\n"
                            + "\n"
                            + "xmlhttp.open('GET', 'http://www.somepage.com/myAjax/xyz', true);\n"
                            + "xmlhttp.send();\n"
                            + "</script>";

                    WebResponseData data = new WebResponseData(content.getBytes("UTF-8"),
                            response.getStatusCode(), response.getStatusMessage(), response.getResponseHeaders());
                    response = new WebResponse(data, request, response.getLoadTime());
                }
                return response;
            }
        };
  1. To retrieve the value of the javascript variable:
webClient.waitForBackgroundJavaScript(5_000);
String value = htmlPage.executeJavaScript("myOwnVariable").toString();
Ahmed Ashour
  • 5,179
  • 10
  • 35
  • 56