com.gargoylesoftware.htmlunit.javascript.host.Window Java Examples

The following examples show how to use com.gargoylesoftware.htmlunit.javascript.host.Window. 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: SimpleScriptable.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Gets a named property from the object.
 * Normally HtmlUnit objects don't need to overwrite this method as properties are defined
 * on the prototypes from the XML configuration. In some cases where "content" of object
 * has priority compared to the properties consider using utility {@link #getWithPreemption(String)}.
 * {@inheritDoc}
 */
@Override
public Object get(String name, final Scriptable start) {
    // If this object is not case-sensitive about property names, transform the property name accordingly.
    if (!caseSensitive_) {
        for (final Object o : getAllIds()) {
            final String objectName = Context.toString(o);
            if (name.equalsIgnoreCase(objectName)) {
                name = objectName;
                break;
            }
        }
    }
    // Try to get property configured on object itself.
    Object response = super.get(name, start);
    if (response != NOT_FOUND) {
        return response;
    }
    if (this == start) {
        response = getWithPreemption(name);
    }
    if (response == NOT_FOUND && start instanceof Window) {
        response = ((Window) start).getWithFallback(name);
    }
    return response;
}
 
Example #2
Source File: DateTimeFormat.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * JavaScript constructor.
 * @param cx the current context
 * @param args the arguments to the WebSocket constructor
 * @param ctorObj the function object
 * @param inNewExpr Is new or not
 * @return the java object to allow JavaScript to access
 */
@JsxConstructor
public static Scriptable jsConstructor(final Context cx, final Object[] args, final Function ctorObj,
        final boolean inNewExpr) {
    final String[] locales;
    if (args.length != 0) {
        if (args[0] instanceof NativeArray) {
            final NativeArray array = (NativeArray) args[0];
            locales = new String[(int) array.getLength()];
            for (int i = 0; i < locales.length; i++) {
                locales[i] = Context.toString(array.get(i));
            }
        }
        else {
            locales = new String[] {Context.toString(args[0])};
        }
    }
    else {
        locales = new String[] {""};
    }
    final Window window = getWindow(ctorObj);
    final DateTimeFormat format = new DateTimeFormat(locales, window.getBrowserVersion());
    format.setParentScope(window);
    format.setPrototype(window.getPrototype(format.getClass()));
    return format;
}
 
Example #3
Source File: MessageEvent.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Initializes an event object.
 * @param type the event type
 * @param canBubble can the event bubble
 * @param cancelable can the event be canceled
 * @param data the message
 * @param origin the scheme, hostname and port of the document that caused the event
 * @param lastEventId the identifier of the last event
 * @param source the window object that contains the document that caused the event
 * @param ports the message ports
 */
@JsxFunction({CHROME, IE, FF})
public void initMessageEvent(
        final String type,
        final boolean canBubble,
        final boolean cancelable,
        final Object data,
        final String origin,
        final String lastEventId,
        final Window source,
        final Object ports) {
    initEvent(type, canBubble, cancelable);
    data_ = data;
    origin_ = origin;
    lastEventId_ = lastEventId;
    source_ = source;
    ports_ = ports;
}
 
Example #4
Source File: HTMLDocument.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the current document instance, using <tt>thisObj</tt> as a hint.
 * @param thisObj a hint as to the current document (may be the prototype when function is used without "this")
 * @return the current document instance
 */
private static HTMLDocument getDocument(final Scriptable thisObj) {
    // if function is used "detached", then thisObj is the top scope (ie Window), not the real object
    // cf unit test DocumentTest#testDocumentWrite_AssignedToVar
    // may be the prototype too
    // cf DocumentTest#testDocumentWrite_AssignedToVar2
    if (thisObj instanceof HTMLDocument && thisObj.getPrototype() instanceof HTMLDocument) {
        return (HTMLDocument) thisObj;
    }
    if (thisObj instanceof DocumentProxy && thisObj.getPrototype() instanceof HTMLDocument) {
        return (HTMLDocument) ((DocumentProxy) thisObj).getDelegee();
    }

    final Window window = getWindow(thisObj);
    if (window.getBrowserVersion().hasFeature(HTMLDOCUMENT_FUNCTION_DETACHED)) {
        return (HTMLDocument) window.getDocument();
    }
    throw Context.reportRuntimeError("Function can't be used detached from document");
}
 
Example #5
Source File: EventTarget.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Executes the event on this object only (needed for instance for onload on (i)frame tags).
 * @param event the event
 * @return the result
 * @see #fireEvent(Event)
 */
public ScriptResult executeEventLocally(final Event event) {
    final EventListenersContainer eventListenersContainer = getEventListenersContainer();
    if (eventListenersContainer != null) {
        final Window window = getWindow();
        final Object[] args = new Object[] {event};

        // handlers declared as property on a node don't receive the event as argument for IE
        final Object[] propHandlerArgs = args;

        final Event previousEvent = window.getCurrentEvent();
        window.setCurrentEvent(event);
        try {
            return eventListenersContainer.executeListeners(event, args, propHandlerArgs);
        }
        finally {
            window.setCurrentEvent(previousEvent); // reset event
        }
    }
    return null;
}
 
Example #6
Source File: SimpleScriptable.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Gets a named property from the object.
 * Normally HtmlUnit objects don't need to overwrite this method as properties are defined
 * on the prototypes from the XML configuration. In some cases where "content" of object
 * has priority compared to the properties consider using utility {@link #getWithPreemption(String)}.
 * {@inheritDoc}
 */
@Override
public Object get(String name, final Scriptable start) {
    // If this object is not case-sensitive about property names, transform the property name accordingly.
    if (!caseSensitive_) {
        for (final Object o : getAllIds()) {
            final String objectName = Context.toString(o);
            if (name.equalsIgnoreCase(objectName)) {
                name = objectName;
                break;
            }
        }
    }
    // Try to get property configured on object itself.
    Object response = super.get(name, start);
    if (response != NOT_FOUND) {
        return response;
    }
    if (this == start) {
        response = getWithPreemption(name);
    }
    if (response == NOT_FOUND && start instanceof Window) {
        response = ((Window) start).getWithFallback(name);
    }
    return response;
}
 
Example #7
Source File: Node.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Encapsulates the given {@link DOMException} into a Rhino-compatible exception.
 *
 * @param exception the exception to encapsulate
 * @return the created exception
 */
protected RhinoException asJavaScriptException(final DOMException exception) {
    final Window w = getWindow();
    exception.setPrototype(w.getPrototype(exception.getClass()));
    exception.setParentScope(w);

    // get current line and file name
    // this method can only be used in interpreted mode. If one day we choose to use compiled mode,
    // then we'll have to find an other way here.
    final String fileName;
    final int lineNumber;
    if (Context.getCurrentContext().getOptimizationLevel() == -1) {
        final int[] linep = new int[1];
        final String sourceName = new Interpreter().getSourcePositionFromStack(Context.getCurrentContext(), linep);
        fileName = sourceName.replaceFirst("script in (.*) from .*", "$1");
        lineNumber = linep[0];
    }
    else {
        throw new Error("HtmlUnit not ready to run in compiled mode");
    }

    exception.setLocation(fileName, lineNumber);

    return new JavaScriptException(exception, fileName, lineNumber);
}
 
Example #8
Source File: CSSStyleSheet.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new stylesheet representing the CSS stylesheet for the specified input source.
 * @param element the owning node
 * @param styleSheet the source which contains the CSS stylesheet which this stylesheet host object represents
 * @param uri this stylesheet's URI (used to resolved contained @import rules)
 */
public CSSStyleSheet(final HTMLElement element, final String styleSheet, final String uri) {
    final Window win = element.getWindow();

    CSSStyleSheetImpl css = null;
    try (InputSource source = new InputSource(new StringReader(styleSheet))) {
        source.setURI(uri);
        css = parseCSS(source, win.getWebWindow().getWebClient());
    }
    catch (final IOException e) {
        LOG.error(e.getMessage(), e);
    }

    setParentScope(win);
    setPrototype(getPrototype(CSSStyleSheet.class));
    wrapped_ = css;
    uri_ = uri;
    ownerNode_ = element;
}
 
Example #9
Source File: Range.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves a collection of rectangles that describes the layout of the contents of an object
 * or range within the client. Each rectangle describes a single line.
 * @return a collection of rectangles that describes the layout of the contents
 */
@JsxFunction
public ClientRectList getClientRects() {
    final Window w = getWindow();
    final ClientRectList rectList = new ClientRectList();
    rectList.setParentScope(w);
    rectList.setPrototype(getPrototype(rectList.getClass()));

    // simple impl for now
    for (DomNode node : toW3C().containedNodes()) {
        final ScriptableObject scriptable = node.getScriptableObject();
        if (scriptable instanceof HTMLElement) {
            final ClientRect rect = new ClientRect(0, 0, 1, 1);
            rect.setParentScope(w);
            rect.setPrototype(getPrototype(rect.getClass()));
            rectList.add(rect);
        }
    }

    return rectList;
}
 
Example #10
Source File: TextRange.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves the parent element for the given text range.
 * The parent element is the element that completely encloses the text in the range.
 * If the text range spans text in more than one element, this method returns the smallest element that encloses
 * all the elements. When you insert text into a range that spans multiple elements, the text is placed in the
 * parent element rather than in any of the contained elements.
 *
 * @see <a href="http://msdn.microsoft.com/en-us/library/ms536654.aspx">MSDN doc</a>
 * @return the parent element object if successful, or null otherwise.
 */
@JsxFunction
public Node parentElement() {
    final org.w3c.dom.Node parent = range_.getCommonAncestorContainer();
    if (null == parent) {
        if (null == range_.getStartContainer() || null == range_.getEndContainer()) {
            try {
                final Window window = (Window) getParentScope();
                final HtmlPage page = (HtmlPage) window.getDomNodeOrDie();
                return (Node) getScriptableFor(page.getBody());
            }
            catch (final Exception e) {
                // ok bad luck
            }
        }
        return null;
    }
    return (Node) getScriptableFor(parent);
}
 
Example #11
Source File: Node.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Encapsulates the given {@link DOMException} into a Rhino-compatible exception.
 *
 * @param exception the exception to encapsulate
 * @return the created exception
 */
protected RhinoException asJavaScriptException(final DOMException exception) {
    final Window w = getWindow();
    exception.setPrototype(w.getPrototype(exception.getClass()));
    exception.setParentScope(w);

    // get current line and file name
    // this method can only be used in interpreted mode. If one day we choose to use compiled mode,
    // then we'll have to find an other way here.
    final String fileName;
    final int lineNumber;
    if (Context.getCurrentContext().getOptimizationLevel() == -1) {
        final int[] linep = new int[1];
        final String sourceName = new Interpreter().getSourcePositionFromStack(Context.getCurrentContext(), linep);
        fileName = sourceName.replaceFirst("script in (.*) from .*", "$1");
        lineNumber = linep[0];
    }
    else {
        throw new Error("HtmlUnit not ready to run in compiled mode");
    }

    exception.setLocation(fileName, lineNumber);

    return new JavaScriptException(exception, fileName, lineNumber);
}
 
Example #12
Source File: EventTarget.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Executes the event on this object only (needed for instance for onload on (i)frame tags).
 * @param event the event
 * @see #fireEvent(Event)
 */
public void executeEventLocally(final Event event) {
    final EventListenersContainer eventListenersContainer = getEventListenersContainer();
    final Window window = getWindow();
    final Object[] args = {event};

    final Event previousEvent = window.getCurrentEvent();
    window.setCurrentEvent(event);
    try {
        event.setEventPhase(Event.AT_TARGET);
        eventListenersContainer.executeAtTargetListeners(event, args);
    }
    finally {
        window.setCurrentEvent(previousEvent); // reset event
    }
}
 
Example #13
Source File: TextRange.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves the parent element for the given text range.
 * The parent element is the element that completely encloses the text in the range.
 * If the text range spans text in more than one element, this method returns the smallest element that encloses
 * all the elements. When you insert text into a range that spans multiple elements, the text is placed in the
 * parent element rather than in any of the contained elements.
 *
 * @see <a href="http://msdn.microsoft.com/en-us/library/ms536654.aspx">MSDN doc</a>
 * @return the parent element object if successful, or null otherwise.
 */
@JsxFunction
public Node parentElement() {
    final org.w3c.dom.Node parent = range_.getCommonAncestorContainer();
    if (null == parent) {
        if (null == range_.getStartContainer() || null == range_.getEndContainer()) {
            try {
                final Window window = (Window) getParentScope();
                final HtmlPage page = (HtmlPage) window.getDomNodeOrDie();
                return (Node) getScriptableFor(page.getBody());
            }
            catch (final Exception e) {
                // ok bad luck
            }
        }
        return null;
    }
    return (Node) getScriptableFor(parent);
}
 
Example #14
Source File: HTMLDocument.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the current document instance, using <tt>thisObj</tt> as a hint.
 * @param thisObj a hint as to the current document (may be the prototype when function is used without "this")
 * @return the current document instance
 */
private static HTMLDocument getDocument(final Scriptable thisObj) {
    // if function is used "detached", then thisObj is the top scope (ie Window), not the real object
    // cf unit test DocumentTest#testDocumentWrite_AssignedToVar
    // may be the prototype too
    // cf DocumentTest#testDocumentWrite_AssignedToVar2
    if (thisObj instanceof HTMLDocument && thisObj.getPrototype() instanceof HTMLDocument) {
        return (HTMLDocument) thisObj;
    }
    if (thisObj instanceof DocumentProxy && thisObj.getPrototype() instanceof HTMLDocument) {
        return (HTMLDocument) ((DocumentProxy) thisObj).getDelegee();
    }

    final Window window = getWindow(thisObj);
    if (window.getBrowserVersion().hasFeature(HTMLDOCUMENT_FUNCTION_DETACHED)) {
        return (HTMLDocument) window.getDocument();
    }
    throw Context.reportRuntimeError("Function can't be used detached from document");
}
 
Example #15
Source File: HTMLDocument.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Sets the specified element as the document's active element.
 * @see HTMLElement#setActive()
 * @param element the new active element for this document
 */
public void setActiveElement(final HTMLElement element) {
    // TODO update page focus element also

    activeElement_ = element;

    if (element != null) {
        // if this is part of an iFrame, make the iFrame tag the
        // active element of his doc
        final WebWindow window = element.getDomNodeOrDie().getPage().getEnclosingWindow();
        if (window instanceof FrameWindow) {
            final BaseFrameElement frame = ((FrameWindow) window).getFrameElement();
            if (frame instanceof HtmlInlineFrame) {
                final Window winWithFrame = frame.getPage().getEnclosingWindow().getScriptableObject();
                ((HTMLDocument) winWithFrame.getDocument()).setActiveElement(
                            (HTMLElement) frame.getScriptableObject());
            }
        }
    }
}
 
Example #16
Source File: Range.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves a collection of rectangles that describes the layout of the contents of an object
 * or range within the client. Each rectangle describes a single line.
 * @return a collection of rectangles that describes the layout of the contents
 */
@JsxFunction
public ClientRectList getClientRects() {
    final Window w = getWindow();
    final ClientRectList rectList = new ClientRectList();
    rectList.setParentScope(w);
    rectList.setPrototype(getPrototype(rectList.getClass()));

    // simple impl for now
    for (DomNode node : toW3C().containedNodes()) {
        final ScriptableObject scriptable = node.getScriptableObject();
        if (scriptable instanceof HTMLElement) {
            final ClientRect rect = new ClientRect(0, 0, 1, 1);
            rect.setParentScope(w);
            rect.setPrototype(getPrototype(rect.getClass()));
            rectList.add(rect);
        }
    }

    return rectList;
}
 
Example #17
Source File: DedicatedWorkerGlobalScope.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Constructor.
 * @param browserVersion the simulated browser version
 * @param worker the started worker
 * @throws Exception in case of problem
 */
DedicatedWorkerGlobalScope(final Window owningWindow, final Context context, final BrowserVersion browserVersion,
        final Worker worker) throws Exception {
    context.initSafeStandardObjects(this);

    ClassConfiguration config = AbstractJavaScriptConfiguration.getClassConfiguration(
            (Class<? extends HtmlUnitScriptable>) DedicatedWorkerGlobalScope.class.getSuperclass(),
            browserVersion);
    final HtmlUnitScriptable parentPrototype = JavaScriptEngine.configureClass(config, null, browserVersion);

    config = AbstractJavaScriptConfiguration.getClassConfiguration(
                            DedicatedWorkerGlobalScope.class, browserVersion);
    final HtmlUnitScriptable prototype = JavaScriptEngine.configureClass(config, null, browserVersion);
    prototype.setPrototype(parentPrototype);
    setPrototype(prototype);

    owningWindow_ = owningWindow;
    final URL currentURL = owningWindow.getWebWindow().getEnclosedPage().getUrl();
    origin_ = currentURL.getProtocol() + "://" + currentURL.getHost() + ':' + currentURL.getPort();

    worker_ = worker;
}
 
Example #18
Source File: AppletClassLoader.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * The constructor.
 * @param window the window containing this applet
 * @param parent the parent class loader for delegation
 */
public AppletClassLoader(final Window window, final ClassLoader parent) {
    super(new URL[0], parent);

    if (window.getWebWindow().getWebClient().getOptions().isUseInsecureSSL()) {
        if (LOG.isWarnEnabled()) {
            LOG.warn("AppletClassLoader: your WebClient accepts ssl connections without certificate checking."
                    + " If you like to load applet archives from a SSL/HTTPS connection you have to configure"
                    + " your jvm to accept untrusted certificate for SSL/HTTPS connections also.");
        }
    }

    try {
        loadOurNetscapeStuff("netscape.javascript.JSException");
        final Class<?> jsObjectClass = loadOurNetscapeStuff("netscape.javascript.JSObject");
        MethodUtils.invokeExactStaticMethod(jsObjectClass, "setWindow", window);
    }
    catch (final Exception e) {
        LOG.error(e.getMessage(), e);
    }
}
 
Example #19
Source File: DateTimeFormat.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * JavaScript constructor.
 * @param cx the current context
 * @param args the arguments to the WebSocket constructor
 * @param ctorObj the function object
 * @param inNewExpr Is new or not
 * @return the java object to allow JavaScript to access
 */
@JsxConstructor
public static Scriptable jsConstructor(final Context cx, final Object[] args, final Function ctorObj,
        final boolean inNewExpr) {
    final String[] locales;
    if (args.length != 0) {
        if (args[0] instanceof NativeArray) {
            final NativeArray array = (NativeArray) args[0];
            locales = new String[(int) array.getLength()];
            for (int i = 0; i < locales.length; i++) {
                locales[i] = Context.toString(array.get(i));
            }
        }
        else {
            locales = new String[] {Context.toString(args[0])};
        }
    }
    else {
        locales = new String[] {""};
    }
    final Window window = getWindow(ctorObj);
    final DateTimeFormat format = new DateTimeFormat(locales, window.getBrowserVersion());
    format.setParentScope(window);
    format.setPrototype(window.getPrototype(format.getClass()));
    return format;
}
 
Example #20
Source File: AudioContext.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * The decodeAudioData() method of the BaseAudioContext Interface is used to asynchronously
 * decode audio file data contained in an ArrayBuffer. In this case the ArrayBuffer is
 * loaded from XMLHttpRequest and FileReader.
 * The decoded AudioBuffer is resampled to the AudioContext's sampling rate,
 * then passed to a callback or promise.
 * @param buffer An ArrayBuffer containing the audio data to be decoded, usually grabbed
 * from XMLHttpRequest, WindowOrWorkerGlobalScope.fetch() or FileReader
 * @param success A callback function to be invoked when the decoding successfully finishes.
 * The single argument to this callback is an AudioBuffer representing the decodedData
 * (the decoded PCM audio data). Usually you'll want to put the decoded data into
 * an AudioBufferSourceNode, from which it can be played and manipulated how you want.
 * @param error An optional error callback, to be invoked if an error occurs
 * when the audio data is being decoded.
 * @return the promise or null
 */
@JsxFunction
public Promise decodeAudioData(final NativeArrayBuffer buffer, final Function success, final Function error) {
    final Window window = getWindow();
    final HtmlPage owningPage = (HtmlPage) window.getDocument().getPage();
    final JavaScriptEngine jsEngine =
            (JavaScriptEngine) window.getWebWindow().getWebClient().getJavaScriptEngine();

    if (error != null) {
        jsEngine.addPostponedAction(new PostponedAction(owningPage) {
            @Override
            public void execute() throws Exception {
                jsEngine.callFunction(owningPage, error, getParentScope(), AudioContext.this, new Object[] {});
            }
        });
        return null;
    }

    final Promise promise = Promise.reject(Context.getCurrentContext(), AudioContext.this, new Object[] {}, null);
    return promise;
}
 
Example #21
Source File: HTMLDocument.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Sets the specified element as the document's active element.
 * @see HTMLElement#setActive()
 * @param element the new active element for this document
 */
public void setActiveElement(final HTMLElement element) {
    // TODO update page focus element also

    activeElement_ = element;

    if (element != null) {
        // if this is part of an iFrame, make the iFrame tag the
        // active element of his doc
        final WebWindow window = element.getDomNodeOrDie().getPage().getEnclosingWindow();
        if (window instanceof FrameWindow) {
            final BaseFrameElement frame = ((FrameWindow) window).getFrameElement();
            if (frame instanceof HtmlInlineFrame) {
                final Window winWithFrame = (Window) frame.getPage().getEnclosingWindow().getScriptableObject();
                ((HTMLDocument) winWithFrame.getDocument()).setActiveElement(
                            (HTMLElement) frame.getScriptableObject());
            }
        }
    }
}
 
Example #22
Source File: History.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Loads the URL at the current index into the window to which this navigation history belongs.
 * @throws IOException if an IO error occurs
 */
private void goToUrlAtCurrentIndex() throws IOException {
    final Boolean old = ignoreNewPages_.get();
    ignoreNewPages_.set(Boolean.TRUE);
    try {

        final HistoryEntry entry = entries_.get(index_);

        final Page page = entry.getPage();
        if (page == null) {
            window_.getWebClient().getPage(window_, entry.getWebRequest(), false);
        }
        else {
            window_.setEnclosedPage(page);
            page.getWebResponse().getWebRequest().setUrl(entry.getUrl());
        }

        final Window jsWindow = window_.getScriptableObject();
        if (jsWindow != null && jsWindow.hasEventHandlers("onpopstate")) {
            final Event event = new PopStateEvent(jsWindow, Event.TYPE_POPSTATE, entry.getState());
            jsWindow.executeEventLocally(event);
        }
    }
    finally {
        ignoreNewPages_.set(old);
    }
}
 
Example #23
Source File: ScriptElementSupport.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Executes this script node as inline script if necessary and/or possible.
 */
private static void executeInlineScriptIfNeeded(final DomElement element) {
    if (!isExecutionNeeded(element)) {
        return;
    }

    final String src = ((ScriptElement) element).getSrcAttribute();
    if (src != ATTRIBUTE_NOT_DEFINED) {
        return;
    }

    final String forr = element.getAttributeDirect("for");
    String event = element.getAttributeDirect("event");
    // The event name can be like "onload" or "onload()".
    if (event.endsWith("()")) {
        event = event.substring(0, event.length() - 2);
    }

    final String scriptCode = getScriptCode(element);
    if (event != ATTRIBUTE_NOT_DEFINED && forr != ATTRIBUTE_NOT_DEFINED) {
        if (element.hasFeature(JS_SCRIPT_SUPPORTS_FOR_AND_EVENT_WINDOW) && "window".equals(forr)) {
            final Window window = element.getPage().getEnclosingWindow().getScriptableObject();
            final BaseFunction function = new EventHandler(element, event, scriptCode);
            window.getEventListenersContainer().addEventListener(StringUtils.substring(event, 2), function, false);
            return;
        }
    }
    if (forr == ATTRIBUTE_NOT_DEFINED || "onload".equals(event)) {
        final String url = element.getPage().getUrl().toExternalForm();
        final int line1 = element.getStartLineNumber();
        final int line2 = element.getEndLineNumber();
        final int col1 = element.getStartColumnNumber();
        final int col2 = element.getEndColumnNumber();
        final String desc = "script in " + url + " from (" + line1 + ", " + col1
            + ") to (" + line2 + ", " + col2 + ")";

        ((ScriptElement) element).setExecuted(true);
        ((HtmlPage) element.getPage()).executeJavaScript(scriptCode, desc, line1);
    }
}
 
Example #24
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 #25
Source File: WebClient.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
 *
 * Initializes a new page for JavaScript.
 * @param newPage the new page
 */
public void initialize(final Page newPage) {
    WebAssert.notNull("newPage", newPage);

    if (isJavaScriptEngineEnabled()) {
        final Window window = newPage.getEnclosingWindow().getScriptableObject();
        window.initialize(newPage);
    }
}
 
Example #26
Source File: ScriptElementSupport.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Executes this script node as inline script if necessary and/or possible.
 */
private static void executeInlineScriptIfNeeded(final DomElement element) {
    if (!isExecutionNeeded(element)) {
        return;
    }

    final String src = ((ScriptElement) element).getSrcAttribute();
    if (src != ATTRIBUTE_NOT_DEFINED) {
        return;
    }

    final String forr = element.getAttributeDirect("for");
    String event = element.getAttributeDirect("event");
    // The event name can be like "onload" or "onload()".
    if (event.endsWith("()")) {
        event = event.substring(0, event.length() - 2);
    }

    final String scriptCode = getScriptCode(element);
    if (event != ATTRIBUTE_NOT_DEFINED && forr != ATTRIBUTE_NOT_DEFINED) {
        if (element.hasFeature(JS_SCRIPT_SUPPORTS_FOR_AND_EVENT_WINDOW) && "window".equals(forr)) {
            final Window window = (Window) element.getPage().getEnclosingWindow().getScriptableObject();
            final BaseFunction function = new EventHandler(element, event, scriptCode);
            window.getEventListenersContainer().addEventListener(StringUtils.substring(event, 2), function, false);
            return;
        }
    }
    if (forr == ATTRIBUTE_NOT_DEFINED || "onload".equals(event)) {
        final String url = element.getPage().getUrl().toExternalForm();
        final int line1 = element.getStartLineNumber();
        final int line2 = element.getEndLineNumber();
        final int col1 = element.getStartColumnNumber();
        final int col2 = element.getEndColumnNumber();
        final String desc = "script in " + url + " from (" + line1 + ", " + col1
            + ") to (" + line2 + ", " + col2 + ")";

        ((ScriptElement) element).setExecuted(true);
        ((HtmlPage) element.getPage()).executeJavaScript(scriptCode, desc, line1);
    }
}
 
Example #27
Source File: Worker.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
private Worker(final Context cx, final Window owningWindow, final String url) throws Exception {
    setParentScope(owningWindow);
    setPrototype(getPrototype(getClass()));

    final WebClient webClient = getWindow().getWebWindow().getWebClient();
    workerScope_ = new DedicatedWorkerGlobalScope(owningWindow, cx, webClient.getBrowserVersion(), this);

    workerScope_.loadAndExecute(webClient, url, null, false);
}
 
Example #28
Source File: RecursiveFunctionObject.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the browser version currently used.
 * @return the browser version
 */
public BrowserVersion getBrowserVersion() {
    Scriptable parent = getParentScope();
    while (!(parent instanceof Window)) {
        parent = parent.getParentScope();
    }
    return ((Window) parent).getBrowserVersion();
}
 
Example #29
Source File: Uint8Array.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Ctor.
 *
 * @param bytes the bytes to store
 * @param window the context
 */
public Uint8Array(final byte[] bytes, final Window window) {
    this();
    setPrototype(window.getPrototype(getClass()));
    setParentScope(getParentScope());

    setByteLength(bytes.length);

    final ArrayBuffer buffer = new ArrayBuffer(bytes);
    buffer.setPrototype(window.getPrototype(buffer.getClass()));
    buffer.setParentScope(getParentScope());
    setBuffer(buffer);
}
 
Example #30
Source File: HtmlScript.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Executes this script node as inline script if necessary and/or possible.
 */
private void executeInlineScriptIfNeeded() {
    if (!isExecutionNeeded()) {
        return;
    }

    final String src = getSrcAttribute();
    if (src != ATTRIBUTE_NOT_DEFINED) {
        return;
    }

    final String forr = getHtmlForAttribute();
    String event = getEventAttribute();
    // The event name can be like "onload" or "onload()".
    if (event.endsWith("()")) {
        event = event.substring(0, event.length() - 2);
    }

    final String scriptCode = getScriptCode();
    if (event != ATTRIBUTE_NOT_DEFINED && forr != ATTRIBUTE_NOT_DEFINED
            && hasFeature(JS_SCRIPT_SUPPORTS_FOR_AND_EVENT_WINDOW) && "window".equals(forr)) {
        final Window window = getPage().getEnclosingWindow().getScriptableObject();
        final BaseFunction function = new EventHandler(this, event, scriptCode);
        window.getEventListenersContainer().addEventListener(StringUtils.substring(event, 2), function, false);
        return;
    }
    if (forr == ATTRIBUTE_NOT_DEFINED || "onload".equals(event)) {
        final String url = getPage().getUrl().toExternalForm();
        final int line1 = getStartLineNumber();
        final int line2 = getEndLineNumber();
        final int col1 = getStartColumnNumber();
        final int col2 = getEndColumnNumber();
        final String desc = "script in " + url + " from (" + line1 + ", " + col1
            + ") to (" + line2 + ", " + col2 + ")";

        executed_ = true;
        ((HtmlPage) getPage()).executeJavaScript(scriptCode, desc, line1);
    }
}