com.gargoylesoftware.htmlunit.ScriptException Java Examples

The following examples show how to use com.gargoylesoftware.htmlunit.ScriptException. 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: JavaScriptEngine.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Performs initialization for the given webWindow.
 * @param webWindow the web window to initialize for
 */
@Override
public void initialize(final WebWindow webWindow) {
    WebAssert.notNull("webWindow", webWindow);

    getContextFactory().call(cx -> {
        try {
            init(webWindow, cx);
        }
        catch (final Exception e) {
            LOG.error("Exception while initializing JavaScript for the page", e);
            throw new ScriptException(null, e); // BUG: null is not useful.
        }
        return null;
    });
}
 
Example #2
Source File: JavaScriptEngineTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
@Alerts(IE = "2")
public void commentNoDoubleSlash() throws Exception {
    final String html =
        "<html><head>\n"
        + "<script><!-- alert(1);\n"
        + " alert(2);\n"
        + "alert(3) --></script>\n"
        + "</head>\n"
        + "<body>\n"
        + "</body></html>";

    boolean exceptionThrown = false;
    try {
        loadPageWithAlerts(html);
    }
    catch (final ScriptException e) {
        exceptionThrown = true;
        assertEquals(4, e.getFailingLineNumber());
    }

    assertEquals(getBrowserVersion().isFirefox() || getBrowserVersion().isChrome(), exceptionThrown);
}
 
Example #3
Source File: HTMLDocument2Test.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void domainTooShort() throws Exception {
    final String html = "<html><head><title>foo</title><script>\n"
        + "function doTest() {\n"
        + "  alert(document.domain);\n"
        + "  document.domain = 'com';\n"
        + "  alert(document.domain);\n"
        + "}\n"
        + "</script></head>\n"
        + "<body onload='doTest()'>\n"
        + "</body></html>";

    final List<String> collectedAlerts = new ArrayList<>();
    try {
        loadPage(getWebClient(), html, collectedAlerts);
    }
    catch (final ScriptException ex) {
        return;
    }
    fail();
}
 
Example #4
Source File: JavaScriptEngine.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Performs initialization for the given webWindow.
 * @param webWindow the web window to initialize for
 */
@Override
public void initialize(final WebWindow webWindow) {
    WebAssert.notNull("webWindow", webWindow);

    final ContextAction action = new ContextAction() {
        @Override
        public Object run(final Context cx) {
            try {
                init(webWindow, cx);
            }
            catch (final Exception e) {
                LOG.error("Exception while initializing JavaScript for the page", e);
                throw new ScriptException(null, e); // BUG: null is not useful.
            }

            return null;
        }
    };

    getContextFactory().call(action);
}
 
Example #5
Source File: JavaScriptEngine.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Handles an exception that occurred during execution of JavaScript code.
 * @param scriptException the exception
 * @param triggerOnError if true, this triggers the onerror handler
 */
protected void handleJavaScriptException(final ScriptException scriptException, final boolean triggerOnError) {
    // Trigger window.onerror, if it has been set.
    final HtmlPage page = scriptException.getPage();
    if (triggerOnError && page != null) {
        final WebWindow window = page.getEnclosingWindow();
        if (window != null) {
            final Window w = window.getScriptableObject();
            if (w != null) {
                try {
                    w.triggerOnError(scriptException);
                }
                catch (final Exception e) {
                    handleJavaScriptException(new ScriptException(page, e, null), false);
                }
            }
        }
    }
    getWebClient().getJavaScriptErrorListener().scriptException(page, scriptException);
    // Throw a Java exception if the user wants us to.
    if (getWebClient().getOptions().isThrowExceptionOnScriptError()) {
        throw scriptException;
    }
    // Log the error; ScriptException instances provide good debug info.
    LOG.info("Caught script exception", scriptException);
}
 
Example #6
Source File: HtmlUnitContextFactory.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Same as {@link ContextFactory}{@link #call(ContextAction)} but with handling
 * of some exceptions.
 *
 * @param <T> return type of the action
 * @param action the contextAction
 * @param page the page
 * @return the result of the call
 */
public final <T> T callSecured(final ContextAction<T> action, final HtmlPage page) {
    try {
        return call(action);
    }
    catch (final StackOverflowError e) {
        webClient_.getJavaScriptErrorListener().scriptException(page, new ScriptException(page, e));
        return null;
    }
}
 
Example #7
Source File: Window.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Triggers the {@code onerror} handler, if one has been set.
 * @param e the error that needs to be reported
 */
public void triggerOnError(final ScriptException e) {
    final Object o = getOnerror();
    if (o instanceof Function) {
        final Function f = (Function) o;
        String msg = e.getMessage();
        final String url = e.getPage().getUrl().toExternalForm();

        final int line = e.getFailingLineNumber();
        final int column = e.getFailingColumnNumber();

        Object jsError = e.getMessage();
        if (e.getCause() instanceof JavaScriptException) {
            msg = "uncaught exception: " + e.getCause().getMessage();
            jsError = ((JavaScriptException) e.getCause()).getValue();
        }
        else if (e.getCause() instanceof EcmaError) {
            msg = "uncaught " + e.getCause().getMessage();

            final EcmaError ecmaError = (EcmaError) e.getCause();
            final Scriptable err = Context.getCurrentContext().newObject(this, "Error");
            ScriptableObject.putProperty(err, "message", ecmaError.getMessage());
            ScriptableObject.putProperty(err, "fileName", ecmaError.sourceName());
            ScriptableObject.putProperty(err, "lineNumber", Integer.valueOf(ecmaError.lineNumber()));
            jsError = err;
        }

        final Object[] args = {msg, url, Integer.valueOf(line), Integer.valueOf(column), jsError};
        f.call(Context.getCurrentContext(), this, this, args);
    }
}
 
Example #8
Source File: JavaScriptEngine.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Handles an exception that occurred during execution of JavaScript code.
 * @param scriptException the exception
 * @param triggerOnError if true, this triggers the onerror handler
 */
protected void handleJavaScriptException(final ScriptException scriptException, final boolean triggerOnError) {
    // shutdown was already called
    final WebClient webClient = getWebClient();
    if (webClient == null) {
        if (LOG.isInfoEnabled()) {
            LOG.info("handleJavaScriptException('" + scriptException.getMessage()
                + "') called after the shutdown of the Javascript engine - exception ignored.");
        }

        return;
    }

    // Trigger window.onerror, if it has been set.
    final HtmlPage page = scriptException.getPage();
    if (triggerOnError && page != null) {
        final WebWindow window = page.getEnclosingWindow();
        if (window != null) {
            final Window w = window.getScriptableObject();
            if (w != null) {
                try {
                    w.triggerOnError(scriptException);
                }
                catch (final Exception e) {
                    handleJavaScriptException(new ScriptException(page, e, null), false);
                }
            }
        }
    }

    webClient.getJavaScriptErrorListener().scriptException(page, scriptException);
    // Throw a Java exception if the user wants us to.
    if (webClient.getOptions().isThrowExceptionOnScriptError()) {
        throw scriptException;
    }
}
 
Example #9
Source File: MSXMLActiveXObjectFactory.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
private XMLDOMDocument createXMLDOMDocument(final WebWindow enclosingWindow) {
    final XMLDOMDocument document = new XMLDOMDocument(enclosingWindow);
    initObject(document);

    try {
        document.setParentScope(enclosingWindow.getScriptableObject());
    }
    catch (final Exception e) {
        LOG.error("Exception while initializing JavaScript for the page", e);
        throw new ScriptException(null, e); // BUG: null is not useful.
    }
    return document;
}
 
Example #10
Source File: MSXMLActiveXObjectFactory.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
private void initObject(final MSXMLScriptable scriptable) {
    try {
        scriptable.setPrototype(environment_.getPrototype(scriptable.getClass()));
        scriptable.setEnvironment(environment_);
    }
    catch (final Exception e) {
        LOG.error("Exception while initializing JavaScript for the page", e);
        throw new ScriptException(null, e); // BUG: null is not useful.
    }
}
 
Example #11
Source File: IEWeirdSyntaxTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
private void doTestWithEvaluatorExceptionExcept(final String html) throws Exception {
    try {
        loadPageWithAlerts2(html);
    }
    catch (final Exception e) {
        if (!(e.getCause() instanceof ScriptException)) {
            throw e;
        }
    }
}
 
Example #12
Source File: JavaScriptEngineTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Test for a javascript which points to a broken gzip encoded file (bug 3563712).
 * @throws Exception if an error occurs
 */
@Test
public void externalScriptBrokenGZipEncoded() throws Exception {
    final MockWebConnection webConnection = getMockWebConnection();

    try (ByteArrayOutputStream bytes = new ByteArrayOutputStream()) {
        final String jsContent = "function doTest() { alert('gZip'); }";
        bytes.write(jsContent.getBytes("ASCII"));

        final List<NameValuePair> headers = new ArrayList<>();
        headers.add(new NameValuePair("Content-Encoding", "gzip"));
        webConnection.setResponse(new URL(URL_FIRST, "foo.js"),
                bytes.toByteArray(), 200, "OK", "text/javascript", headers);
    }

    final String htmlContent
        = "<html><head>\n"
        + "<title>foo</title>\n"
        + "<script src='/foo.js'></script>\n"
        + "</head><body onload='doTest();alert(\"done\");'>\n"
        + "</body></html>";

    try {
        loadPageWithAlerts(htmlContent);
        fail("ScriptException expected");
    }
    catch (final ScriptException e) {
        // expected
    }
}
 
Example #13
Source File: Window.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Triggers the {@code onerror} handler, if one has been set.
 * @param e the error that needs to be reported
 */
public void triggerOnError(final ScriptException e) {
    final Object o = getOnerror();
    if (o instanceof Function) {
        final Function f = (Function) o;
        String msg = e.getMessage();
        final String url = e.getPage().getUrl().toExternalForm();

        final int line = e.getFailingLineNumber();
        final int column = e.getFailingColumnNumber();

        Object jsError = e.getMessage();
        if (e.getCause() instanceof JavaScriptException) {
            msg = "uncaught exception: " + e.getCause().getMessage();
            jsError = ((JavaScriptException) e.getCause()).getValue();
        }
        else if (e.getCause() instanceof EcmaError) {
            msg = "uncaught " + e.getCause().getMessage();

            final EcmaError ecmaError = (EcmaError) e.getCause();
            final Scriptable err = Context.getCurrentContext().newObject(this, "Error");
            ScriptableObject.putProperty(err, "message", ecmaError.getMessage());
            ScriptableObject.putProperty(err, "fileName", ecmaError.sourceName());
            ScriptableObject.putProperty(err, "lineNumber", Integer.valueOf(ecmaError.lineNumber()));
            jsError = err;
        }

        final Object[] args = new Object[] {msg, url, Integer.valueOf(line), Integer.valueOf(column), jsError};
        f.call(Context.getCurrentContext(), this, this, args);
    }
}
 
Example #14
Source File: MSXMLActiveXObjectFactory.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
private XMLDOMDocument createXMLDOMDocument(final WebWindow enclosingWindow) {
    final XMLDOMDocument document = new XMLDOMDocument(enclosingWindow);
    initObject(document);

    try {
        document.setParentScope((Scriptable) enclosingWindow.getScriptableObject());
    }
    catch (final Exception e) {
        LOG.error("Exception while initializing JavaScript for the page", e);
        throw new ScriptException(null, e); // BUG: null is not useful.
    }
    return document;
}
 
Example #15
Source File: MSXMLActiveXObjectFactory.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
private void initObject(final MSXMLScriptable scriptable) {
    try {
        scriptable.setPrototype(environment_.getPrototype(scriptable.getClass()));
        scriptable.setEnvironment(environment_);
    }
    catch (final Exception e) {
        LOG.error("Exception while initializing JavaScript for the page", e);
        throw new ScriptException(null, e); // BUG: null is not useful.
    }
}