Java Code Examples for com.gargoylesoftware.htmlunit.html.HtmlPage#executeJavaScript()

The following examples show how to use com.gargoylesoftware.htmlunit.html.HtmlPage#executeJavaScript() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JSObject.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Evaluates a JavaScript expression.
 * The expression is a string of JavaScript source code which will be evaluated in the context given by "this".
 *
 * @param expression the JavaScript expression
 * @return result Object
 * @throws JSException in case or error
 */
public Object eval(final String expression) throws JSException {
    if (LOG.isInfoEnabled()) {
        LOG.info("JSObject eval '" + expression + "'");
    }

    final Page page = Window_.getWebWindow().getEnclosedPage();
    if (page instanceof HtmlPage) {
        final HtmlPage htmlPage = (HtmlPage) page;
        final ScriptResult result = htmlPage.executeJavaScript(expression);
        final Object jsResult = result.getJavaScriptResult();
        if (jsResult instanceof ScriptableObject) {
            return new JSObject((ScriptableObject) jsResult);
        }
        if (jsResult instanceof ConsString) {
            return ((ConsString) jsResult).toString();
        }
        return jsResult;
    }
    return null;
}
 
Example 2
Source File: JSObject.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Evaluates a JavaScript expression.
 * The expression is a string of JavaScript source code which will be evaluated in the context given by "this".
 *
 * @param expression the JavaScript expression
 * @return result Object
 * @throws JSException in case or error
 */
public Object eval(final String expression) throws JSException {
    if (LOG.isInfoEnabled()) {
        LOG.info("JSObject eval '" + expression + "'");
    }

    final Page page = Window_.getWebWindow().getEnclosedPage();
    if (page instanceof HtmlPage) {
        final HtmlPage htmlPage = (HtmlPage) page;
        final ScriptResult result = htmlPage.executeJavaScript(expression);
        final Object jsResult = result.getJavaScriptResult();
        if (jsResult instanceof ScriptableObject) {
            return new JSObject((ScriptableObject) jsResult);
        }
        if (jsResult instanceof ConsString) {
            return ((ConsString) jsResult).toString();
        }
        return jsResult;
    }
    return null;
}
 
Example 3
Source File: HTMLFormElement2Test.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void formSubmit_target() throws Exception {
    final String html
        = "<html><head><title>first</title></head><body>\n"
        + "<p>hello world</p>\n"
        + "<form name='form1' method='get' action='" + URL_SECOND + "' target='MyNewWindow'>\n"
        + "  <input type='button' name='button1' />\n"
        + "</form>\n"
        + "</body></html>";
    final String secondContent
        = "<html><head><title>second</title></head><body>\n"
        + "<p>hello world</p>\n"
        + "</body></html>";

    getMockWebConnection().setDefaultResponse(secondContent);

    final HtmlPage page = loadPageWithAlerts(html);

    page.executeJavaScript("document.form1.submit()");
    final HtmlPage secondPage = (HtmlPage) getWebClient().getCurrentWindow().getEnclosedPage();

    assertEquals("second", secondPage.getTitleText());
    assertEquals("MyNewWindow", secondPage.getEnclosingWindow().getName());
}
 
Example 4
Source File: HTMLFormElement2Test.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
@Alerts("javaScript")
public void formSubmitWithJavascriptMixedCase() throws Exception {
    final String html
        = "<html><head><title>first</title></head><body>\n"
        + "<p>hello world</p>\n"
        + "<form name='form1' method='get' action='javaSCript:alert(\"javaScript\")'>\n"
        + "  <input type='button' name='button1' />\n"
        + "  <input type='button' name='button2' />\n"
        + "</form>\n"
        + "</body></html>";

    final List<String> collectedAlerts = new ArrayList<>();

    final HtmlPage page1 = loadPage(html, collectedAlerts);
    page1.executeJavaScript("document.form1.submit()");
    final HtmlPage page2 = (HtmlPage) getWebClient().getCurrentWindow().getEnclosedPage();

    assertEquals(page1, page2);
    assertEquals(getExpectedAlerts(), collectedAlerts);
}
 
Example 5
Source File: HTMLFormElement2Test.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
@Alerts("javaScript")
public void formSubmitWithJavascriptLeadingWhitespace() throws Exception {
    final String html
        = "<html><head><title>first</title></head><body>\n"
        + "<p>hello world</p>\n"
        + "<form name='form1' method='get' action='  javascript:alert(\"javaScript\")'>\n"
        + "  <input type='button' name='button1' />\n"
        + "  <input type='button' name='button2' />\n"
        + "</form>\n"
        + "</body></html>";

    final List<String> collectedAlerts = new ArrayList<>();

    final HtmlPage page1 = loadPage(html, collectedAlerts);
    page1.executeJavaScript("document.form1.submit()");
    final HtmlPage page2 = (HtmlPage) getWebClient().getCurrentWindow().getEnclosedPage();

    assertEquals(page1, page2);
    assertEquals(getExpectedAlerts(), collectedAlerts);
}
 
Example 6
Source File: HTMLFormElement2Test.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
@Alerts("javaScript")
public void formSubmitWithJavascript() throws Exception {
    final String html
        = "<html><head><title>first</title></head><body>\n"
        + "<p>hello world</p>\n"
        + "<form name='form1' method='get' action='javascript:alert(\"javaScript\")'>\n"
        + "  <input type='button' name='button1' />\n"
        + "  <input type='button' name='button2' />\n"
        + "</form>\n"
        + "</body></html>";

    final List<String> collectedAlerts = new ArrayList<>();

    final HtmlPage page1 = loadPage(html, collectedAlerts);
    page1.executeJavaScript("document.form1.submit()");
    final HtmlPage page2 = (HtmlPage) getWebClient().getCurrentWindow().getEnclosedPage();

    assertEquals(page1, page2);
    assertEquals(getExpectedAlerts(), collectedAlerts);
}
 
Example 7
Source File: HTMLFormElement2Test.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void formSubmit() throws Exception {
    final String html
        = "<html><head><title>first</title></head><body>\n"
        + "<p>hello world</p>\n"
        + "<form name='form1' method='get' action='" + URL_SECOND + "'>\n"
        + "  <input type='button' name='button1' />\n"
        + "  <input type='button' name='button2' />\n"
        + "</form>\n"
        + "</body></html>";
    final String secondContent
        = "<html><head><title>second</title></head><body>\n"
        + "<p>hello world</p>\n"
        + "</body></html>";

    getMockWebConnection().setDefaultResponse(secondContent);
    final HtmlPage page = loadPageWithAlerts(html);

    page.executeJavaScript("document.form1.submit()");
    final HtmlPage secondPage = (HtmlPage) getWebClient().getCurrentWindow().getEnclosedPage();
    assertEquals("second", secondPage.getTitleText());
}
 
Example 8
Source File: WebClient2Test.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * As of HtmlUnit-2.7-SNAPSHOT from 24.09.09, loading about:blank in a page didn't
 * reinitialized the window host object.
 * @throws Exception if an error occurs
 */
@Test
public void newWindowScopeForAboutBlank() throws Exception {
    final HtmlPage p = loadPage("<html><body></body></html>");
    p.executeJavaScript("top.foo = 'hello';");
    final ScriptResult result = p.executeJavaScript("top.foo");
    assertEquals("hello", result.getJavaScriptResult());

    final HtmlPage page2 = p.getWebClient().getPage("about:blank");
    final ScriptResult result2 = page2.executeJavaScript("String(top.foo)");
    assertEquals("undefined", result2.getJavaScriptResult());
}
 
Example 9
Source File: Location.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the location URL to an entirely new value.
 * @param newLocation the new location URL
 * @throws IOException if loading the specified location fails
 * @see <a href="http://msdn.microsoft.com/en-us/library/ms533867.aspx">MSDN Documentation</a>
 */
@JsxSetter
public void setHref(final String newLocation) throws IOException {
    final HtmlPage page = (HtmlPage) getWindow(getStartingScope()).getWebWindow().getEnclosedPage();
    if (newLocation.startsWith(JavaScriptURLConnection.JAVASCRIPT_PREFIX)) {
        final String script = newLocation.substring(11);
        page.executeJavaScript(script, "new location value", 1);
        return;
    }
    try {
        URL url = page.getFullyQualifiedUrl(newLocation);
        // fix for empty url
        if (StringUtils.isEmpty(newLocation)) {
            final boolean dropFilename = page.getWebClient().getBrowserVersion().
                    hasFeature(ANCHOR_EMPTY_HREF_NO_FILENAME);
            if (dropFilename) {
                String path = url.getPath();
                path = path.substring(0, path.lastIndexOf('/') + 1);
                url = UrlUtils.getUrlWithNewPath(url, path);
                url = UrlUtils.getUrlWithNewRef(url, null);
            }
            else {
                url = UrlUtils.getUrlWithNewRef(url, null);
            }
        }

        final WebRequest request = new WebRequest(url);
        request.setAdditionalHeader(HttpHeader.REFERER, page.getUrl().toExternalForm());

        final WebWindow webWindow = window_.getWebWindow();
        webWindow.getWebClient().download(webWindow, "", request, true, false, "JS set location");
    }
    catch (final MalformedURLException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("setHref('" + newLocation + "') got MalformedURLException", e);
        }
        throw e;
    }
}
 
Example 10
Source File: JavaScriptStringJob.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
protected void runJavaScript(final HtmlPage page) {
    if (script_ == null) {
        return;
    }
    page.executeJavaScript(script_, "JavaScriptStringJob", 1);
}
 
Example 11
Source File: Version.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Runs the sanity check.
 * @throws Exception if anything goes wrong
 */
private static void runSanityCheck() throws Exception {
    try (WebClient webClient = new WebClient()) {
        final HtmlPage page = webClient.getPage("http://htmlunit.sourceforge.net/index.html");
        page.executeJavaScript("document.location");
        System.out.println("Sanity check complete.");
    }
}
 
Example 12
Source File: HtmlUnitRegExpProxy2Test.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Test that string.replace works correctly (?) in HtmlUnit.
 * @throws Exception if the test fails
 */
@Test
public void fixedInHtmlUnit() throws Exception {
    final String html = "<html></html>";
    final HtmlPage page = loadPage(html);
    final ScriptableObject topScope = page.getEnclosingWindow().getScriptableObject();
    topScope.put("str", topScope, str_);
    topScope.put("text", topScope, text_);
    topScope.put("expected", topScope, expected_);
    page.executeJavaScript(src_);
}
 
Example 13
Source File: HtmlUnitRegExpProxy2Test.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void emptySubStringChanged() throws Exception {
    final String html = "<html></html>";
    final HtmlPage page = loadPage(html);
    page.executeJavaScript("'alpha'.replace(/alpha/, '');/beta/.test('abc beta def');");
}
 
Example 14
Source File: Version.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Runs the sanity check.
 * @throws Exception if anything goes wrong
 */
private static void runSanityCheck() throws Exception {
    try (WebClient webClient = new WebClient()) {
        final HtmlPage page = webClient.getPage("http://htmlunit.sourceforge.net/index.html");
        page.executeJavaScript("document.location");
        System.out.println("Sanity check complete.");
    }
}
 
Example 15
Source File: JavaScriptStringJob.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
protected void runJavaScript(final HtmlPage page) {
    if (script_ == null) {
        return;
    }
    page.executeJavaScript(script_, "JavaScriptStringJob", 1);
}
 
Example 16
Source File: Location.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the location URL to an entirely new value.
 * @param newLocation the new location URL
 * @throws IOException if loading the specified location fails
 * @see <a href="http://msdn.microsoft.com/en-us/library/ms533867.aspx">MSDN Documentation</a>
 */
@JsxSetter
public void setHref(final String newLocation) throws IOException {
    final HtmlPage page = (HtmlPage) getWindow(getStartingScope()).getWebWindow().getEnclosedPage();
    if (newLocation.startsWith(JavaScriptURLConnection.JAVASCRIPT_PREFIX)) {
        final String script = newLocation.substring(11);
        page.executeJavaScript(script, "new location value", 1);
        return;
    }
    try {
        URL url = page.getFullyQualifiedUrl(newLocation);
        // fix for empty url
        if (StringUtils.isEmpty(newLocation)) {
            final boolean dropFilename = page.getWebClient().getBrowserVersion().
                    hasFeature(ANCHOR_EMPTY_HREF_NO_FILENAME);
            if (dropFilename) {
                String path = url.getPath();
                path = path.substring(0, path.lastIndexOf('/') + 1);
                url = UrlUtils.getUrlWithNewPath(url, path);
                url = UrlUtils.getUrlWithNewRef(url, null);
            }
            else {
                url = UrlUtils.getUrlWithNewRef(url, null);
            }
        }

        final WebRequest request = new WebRequest(url);
        request.setAdditionalHeader(HttpHeader.REFERER, page.getUrl().toExternalForm());

        final WebWindow webWindow = window_.getWebWindow();
        webWindow.getWebClient().download(webWindow, "", request, true, false, "JS set location");
    }
    catch (final MalformedURLException e) {
        LOG.error("setHref('" + newLocation + "') got MalformedURLException", e);
        throw e;
    }
}
 
Example 17
Source File: JavascriptWithHtmlUnit.java    From chuidiang-ejemplos with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
   WebClient webClient = new WebClient();
   HtmlPage page = webClient.getPage("file:files/JavascriptWithHtmlUnit.html");
   
   // Sale "hola", puesto que se ha ejecutado el codigo javascript de la pagina
   System.out.println(page.getElementById("unDiv").getTextContent());
   
   // Cambiamos el contenido usando funciones est�ndar de javascript en navegador
   page.executeJavaScript("document.getElementById(\"unDiv\").innerHTML=\"que tal?\"");
   System.out.println(page.getElementById("unDiv").getTextContent());
   
   // Cambiamos el contenido con una funcion javascript definida en la pagina.
   page.executeJavaScript("cambia(\"adios\")");
   System.out.println(page.getElementById("unDiv").getTextContent());
}
 
Example 18
Source File: IntegrationTest.java    From warnings-ng-plugin with MIT License 3 votes vote down vote up
/**
 * Returns the model of a chart in the specified HTML page.
 *
 * @param page
 *         the HTML page that contains the chart
 * @param id
 *         the element ID of the chart placeholder (that has the EChart instance attached in property @{@code
 *         echart}
 *
 * @return the model (as JSON representation)
 */
protected String getChartModel(final HtmlPage page, final String id) {
    ScriptResult scriptResult = page.executeJavaScript(
            String.format("JSON.stringify(document.getElementById(\"%s\").echart.getOption());", id));

    return scriptResult.getJavaScriptResult().toString();
}