net.sourceforge.htmlunit.corejs.javascript.Scriptable Java Examples

The following examples show how to use net.sourceforge.htmlunit.corejs.javascript.Scriptable. 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: XMLHttpRequest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Invokes the onerror handler if one has been set.
 * @param context the context within which the onerror handler is to be invoked;
 *                if {@code null}, the current thread's context is used.
 */
private void processError(Context context) {
    final Function onError = getOnerror();
    if (onError != null) {
        final Scriptable scope = onError.getParentScope();
        final JavaScriptEngine jsEngine = (JavaScriptEngine) containingPage_.getWebClient().getJavaScriptEngine();

        final Object[] params = {new ProgressEvent(this, Event.TYPE_ERROR)};

        if (LOG.isDebugEnabled()) {
            LOG.debug("Calling onerror handler");
        }
        jsEngine.callFunction(containingPage_, onError, this, scope, params);
        if (LOG.isDebugEnabled()) {
            if (context == null) {
                context = Context.getCurrentContext();
            }
            LOG.debug("onerror handler: " + context.decompileFunction(onError, 4));
            LOG.debug("Calling onerror handler done.");
        }
    }
}
 
Example #2
Source File: EventListenersContainer.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Adds an event listener.
 *
 * @param type the event type to listen for (like "load")
 * @param listener the event listener
 * @param useCapture If {@code true}, indicates that the user wishes to initiate capture (not yet implemented)
 * @return {@code true} if the listener has been added
 */
public boolean addEventListener(final String type, final Scriptable listener, final boolean useCapture) {
    if (null == listener) {
        return true;
    }

    final TypeContainer container = getTypeContainer(type);
    final boolean added = container.addListener(listener, useCapture);
    if (!added) {
        if (LOG.isDebugEnabled()) {
            LOG.debug(type + " listener already registered, skipping it (" + listener + ")");
        }
        return false;
    }
    return true;
}
 
Example #3
Source File: DateCustom.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Converts a date to a string, returning the "date" portion using the operating system's locale's conventions.
 * @param context the JavaScript context
 * @param thisObj the scriptable
 * @param args the arguments passed into the method
 * @param function the function
 * @return converted string
 */
public static String toLocaleDateString(
        final Context context, final Scriptable thisObj, final Object[] args, final Function function) {
    final String formatString;
    final BrowserVersion browserVersion = ((Window) thisObj.getParentScope()).getBrowserVersion();

    if (browserVersion.hasFeature(JS_DATE_WITH_LEFT_TO_RIGHT_MARK)) {
        // [U+200E] -> Unicode Character 'LEFT-TO-RIGHT MARK'
        formatString = "\u200EM\u200E/\u200Ed\u200E/\u200Eyyyy";
    }
    else if (browserVersion.hasFeature(JS_DATE_LOCALE_DATE_SHORT)) {
        formatString = "M/d/yyyy";
    }
    else {
        formatString = "EEEE, MMMM dd, yyyy";
    }
    final FastDateFormat format =  FastDateFormat.getInstance(formatString, getLocale(browserVersion));
    return format.format(getDateValue(thisObj));
}
 
Example #4
Source File: DateCustom.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Converts a date to a string, returning the "date" portion using the operating system's locale's conventions.
 * @param context the JavaScript context
 * @param thisObj the scriptable
 * @param args the arguments passed into the method
 * @param function the function
 * @return converted string
 */
public static String toLocaleDateString(
        final Context context, final Scriptable thisObj, final Object[] args, final Function function) {
    final String formatString;
    final BrowserVersion browserVersion = ((Window) thisObj.getParentScope()).getBrowserVersion();

    if (browserVersion.hasFeature(JS_DATE_WITH_LEFT_TO_RIGHT_MARK)) {
        // [U+200E] -> Unicode Character 'LEFT-TO-RIGHT MARK'
        formatString = "\u200EM\u200E/\u200Ed\u200E/\u200Eyyyy";
    }
    else if (browserVersion.hasFeature(JS_DATE_LOCALE_DATE_SHORT)) {
        formatString = "M/d/yyyy";
    }
    else {
        formatString = "EEEE, MMMM dd, yyyy";
    }
    final FastDateFormat format =  FastDateFormat.getInstance(formatString, getLocale(browserVersion));
    return format.format(getDateValue(thisObj));
}
 
Example #5
Source File: HTMLOptionsCollection.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the object at the specified index.
 *
 * @param index the index
 * @param start the object that get is being called on
 * @return the object or NOT_FOUND
 */
@Override
public Object get(final int index, final Scriptable start) {
    if (htmlSelect_ == null || index < 0) {
        return Undefined.instance;
    }

    if (index >= htmlSelect_.getOptionSize()) {
        if (getBrowserVersion().hasFeature(JS_SELECT_OPTIONS_NULL_FOR_OUTSIDE)) {
            return null;
        }
        return Undefined.instance;
    }

    return getScriptableFor(htmlSelect_.getOption(index));
}
 
Example #6
Source File: Node.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Inserts a set of Node or DOMString objects in the children list of this ChildNode's parent,
 * just after this ChildNode.
 * @param context the context
 * @param thisObj this object
 * @param args the arguments
 * @param function the function
 */
protected static void after(final Context context, final Scriptable thisObj, final Object[] args,
        final Function function) {
    final DomNode thisDomNode = ((Node) thisObj).getDomNodeOrDie();
    final DomNode parentNode = thisDomNode.getParentNode();
    final DomNode nextSibling = thisDomNode.getNextSibling();
    for (Object arg : args) {
        final Node node = toNodeOrTextNode((Node) thisObj, arg);
        final DomNode newNode = node.getDomNodeOrDie();
        if (nextSibling != null) {
            nextSibling.insertBefore(newNode);
        }
        else {
            parentNode.appendChild(newNode);
        }
    }
}
 
Example #7
Source File: XMLHTTPRequest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Sets the state as specified and invokes the state change handler if one has been set.
 * @param state the new state
 * @param context the context within which the state change handler is to be invoked;
 *     if {@code null}, the current thread's context is used
 */
private void setState(final int state, Context context) {
    state_ = state;

    if (stateChangeHandler_ != null && !openedMultipleTimes_) {
        final Scriptable scope = stateChangeHandler_.getParentScope();
        final JavaScriptEngine jsEngine = (JavaScriptEngine) containingPage_.getWebClient().getJavaScriptEngine();

        if (LOG.isDebugEnabled()) {
            LOG.debug("Calling onreadystatechange handler for state " + state);
        }
        final Object[] params = ArrayUtils.EMPTY_OBJECT_ARRAY;

        jsEngine.callFunction(containingPage_, stateChangeHandler_, scope, this, params);
        if (LOG.isDebugEnabled()) {
            if (context == null) {
                context = Context.getCurrentContext();
            }
            LOG.debug("onreadystatechange handler: " + context.decompileFunction(stateChangeHandler_, 4));
            LOG.debug("Calling onreadystatechange handler for state " + state + ". Done.");
        }
    }
}
 
Example #8
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 #9
Source File: Console.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
private static WebConsole toWebConsole(Scriptable thisObj) {
    if (thisObj instanceof Window
            && ((SimpleScriptable) thisObj).getDomNodeOrDie().hasFeature(JS_CONSOLE_HANDLE_WINDOW)) {
        thisObj = ((Window) thisObj).getConsole();
    }
    if (thisObj instanceof Console) {
        return ((Console) thisObj).getWebConsole();
    }
    throw Context.reportRuntimeError("TypeError: object does not implemennt interface Console");
}
 
Example #10
Source File: NamedNodeMap.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Object get(final String name, final Scriptable start) {
    Object response = super.get(name, start);
    if (response != NOT_FOUND) {
        return response;
    }

    response = getNamedItem(name);
    if (response != null) {
        return response;
    }

    return NOT_FOUND;
}
 
Example #11
Source File: WebSocket.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
private void callFunction(final Function function, final Object[] args) {
    if (function == null) {
        return;
    }
    final Scriptable scope = function.getParentScope();
    final JavaScriptEngine engine
        = (JavaScriptEngine) containingPage_.getWebClient().getJavaScriptEngine();
    engine.callFunction(containingPage_, function, scope, this, args);
}
 
Example #12
Source File: Window.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
@Override
protected Scriptable getScriptableForElement(final Object obj) {
    final WebWindow window;
    if (obj instanceof BaseFrameElement) {
        window = ((BaseFrameElement) obj).getEnclosedWindow();
    }
    else {
        window = ((FrameWindow) obj).getFrameElement().getEnclosedWindow();
    }

    return window.getScriptableObject();
}
 
Example #13
Source File: HtmlUnitRegExpProxy.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Calls action on the wrapped RegExp proxy.
 */
private Object wrappedAction(final Context cx, final Scriptable scope, final Scriptable thisObj,
        final Object[] args, final int actionType) {

    // take care to set the context's RegExp proxy to the original one as this is checked
    // (cf net.sourceforge.htmlunit.corejs.javascript.regexp.RegExpImp:334)
    try {
        ScriptRuntime.setRegExpProxy(cx, wrapped_);
        return wrapped_.action(cx, scope, thisObj, args, actionType);
    }
    finally {
        ScriptRuntime.setRegExpProxy(cx, this);
    }
}
 
Example #14
Source File: JavaScriptEngine.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Calls a JavaScript function and return the result.
 * @param page the page
 * @param javaScriptFunction the function to call
 * @param thisObject the this object for class method calls
 * @param args the list of arguments to pass to the function
 * @param node the HTML element that will act as the context
 * @return the result of the function call
 */
public Object callFunction(
        final HtmlPage page,
        final Function javaScriptFunction,
        final Scriptable thisObject,
        final Object[] args,
        final DomNode node) {

    final Scriptable scope = getScope(page, node);

    return callFunction(page, javaScriptFunction, scope, thisObject, args);
}
 
Example #15
Source File: Console.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * This method performs logging to the console at {@code debug} level.
 * @param cx the JavaScript context
 * @param thisObj the scriptable
 * @param args the arguments passed into the method
 * @param funObj the function
 */
@JsxFunction
public static void debug(final Context cx, final Scriptable thisObj,
    final Object[] args, final Function funObj) {
    final WebConsole webConsole = toWebConsole(thisObj);
    final Formatter oldFormatter = webConsole.getFormatter();
    webConsole.setFormatter(FORMATTER_);
    webConsole.debug(args);
    webConsole.setFormatter(oldFormatter);
}
 
Example #16
Source File: MethodWrapper.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Converts JavaScript arguments to Java arguments.
 * @param context the current context
 * @param scope the current scope
 * @param jsArgs the JavaScript arguments
 * @return the java arguments
 */
Object[] convertJSArgsToJavaArgs(final Context context, final Scriptable scope, final Object[] jsArgs) {
    if (jsArgs.length != jsTypeTags_.length) {
        throw Context.reportRuntimeError("Bad number of parameters for function " + method_.getName()
                + ": expected " + jsTypeTags_.length + " got " + jsArgs.length);
    }
    final Object[] javaArgs = new Object[jsArgs.length];
    int i = 0;
    for (final Object object : jsArgs) {
        javaArgs[i] = FunctionObject.convertArg(context, scope, object, jsTypeTags_[i++]);
    }
    return javaArgs;
}
 
Example #17
Source File: Uint32Array.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected Object fromArray(final byte[] array, final int offset) {
    if (offset < 0 || offset >= array.length) {
        return Scriptable.NOT_FOUND;
    }
    final ByteBuffer buff = ByteBuffer.wrap(array);
    buff.order(ByteOrder.LITTLE_ENDIAN);
    return buff.getInt(offset) & 0xFFFFFFFFL;
}
 
Example #18
Source File: Console.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * This method performs logging to the console at {@code debug} level.
 * @param cx the JavaScript context
 * @param thisObj the scriptable
 * @param args the arguments passed into the method
 * @param funObj the function
 */
@JsxFunction
public static void debug(final Context cx, final Scriptable thisObj,
    final Object[] args, final Function funObj) {
    final WebConsole webConsole = toWebConsole(thisObj);
    final Formatter oldFormatter = webConsole.getFormatter();
    webConsole.setFormatter(FORMATTER_);
    webConsole.debug(args);
    webConsole.setFormatter(oldFormatter);
}
 
Example #19
Source File: Console.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * This method performs logging to the console at {@code warn} level.
 * @param cx the JavaScript context
 * @param thisObj the scriptable
 * @param args the arguments passed into the method
 * @param funObj the function
 */
@JsxFunction
public static void warn(final Context cx, final Scriptable thisObj,
    final Object[] args, final Function funObj) {
    final WebConsole webConsole = toWebConsole(thisObj);
    final Formatter oldFormatter = webConsole.getFormatter();
    webConsole.setFormatter(FORMATTER_);
    webConsole.warn(args);
    webConsole.setFormatter(oldFormatter);
}
 
Example #20
Source File: Set.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Object get(final String name, final Scriptable start) {
    // A hack to handle Rhino not supporting "get(Object object, Scriptable start)"
    if (name.equals(Symbol.ITERATOR_STRING)) {
        return ScriptableObject.getProperty(start, "values");
    }
    return super.get(name, start);
}
 
Example #21
Source File: Promise.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
private static Promise create(final Scriptable thisObj, final Object[] args, final PromiseState state) {
    // fulfilled promises are returned
    if (args.length != 0 && args[0] instanceof Promise && state == PromiseState.FULFILLED) {
        return (Promise) args[0];
    }

    final Promise promise;
    if (args.length > 0) {
        final Object arg = args[0];
        if (arg instanceof NativeObject) {
            final NativeObject nativeObject = (NativeObject) arg;
            final Object thenFunction = nativeObject.get("then", nativeObject);
            if (thenFunction != NOT_FOUND) {
                promise = new Promise(thenFunction);
            }
            else {
                promise = new Promise();
                promise.value_ = arg;
                promise.state_ = state;
            }
        }
        else {
            promise = new Promise();
            promise.value_ = arg;
            promise.state_ = state;
        }
    }
    else {
        promise = new Promise();
        promise.value_ = Undefined.instance;
        promise.state_ = state;
    }

    promise.setParentScope(thisObj.getParentScope());
    promise.setPrototype(getWindow(thisObj).getPrototype(promise.getClass()));
    return promise;
}
 
Example #22
Source File: JavaScriptEngine.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Script compile(final HtmlPage page, final String sourceCode,
                       final String sourceName, final int startLine) {
    final Scriptable scope = getScope(page, null);
    return compile(page, scope, sourceCode, sourceName, startLine);
}
 
Example #23
Source File: WindowOrWorkerGlobalScopeMixin.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Sets a chunk of JavaScript to be invoked each time a specified number of milliseconds has elapsed.
 *
 * @see <a href="https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval">
 * MDN web docs</a>
 * @param context the JavaScript context
 * @param thisObj the scriptable
 * @param args the arguments passed into the method
 * @param function the function
 * @return the id of the created interval
 */
public static Object setInterval(final Context context, final Scriptable thisObj,
        final Object[] args, final Function function) {
    if (args.length < 1) {
        throw ScriptRuntime.typeError("Function not provided");
    }

    final int timeout = ScriptRuntime.toInt32((args.length > 1) ? args[1] : Undefined.instance);
    final Object[] params = (args.length > 2)
            ? Arrays.copyOfRange(args, 2, args.length)
            : ScriptRuntime.emptyArgs;
    return setTimeoutIntervalImpl((Window) thisObj, args[0], timeout, false, params);
}
 
Example #24
Source File: SimpleScriptable.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the prototype object for the given host class.
 * @param javaScriptClass the host class
 * @return the prototype
 */
@SuppressWarnings("unchecked")
public Scriptable getPrototype(final Class<? extends SimpleScriptable> javaScriptClass) {
    final Scriptable prototype = getWindow().getPrototype(javaScriptClass);
    if (prototype == null && javaScriptClass != SimpleScriptable.class) {
        return getPrototype((Class<? extends SimpleScriptable>) javaScriptClass.getSuperclass());
    }
    return prototype;
}
 
Example #25
Source File: Console.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * This method performs logging to the console at {@code error} level.
 * @param cx the JavaScript context
 * @param thisObj the scriptable
 * @param args the arguments passed into the method
 * @param funObj the function
 */
@JsxFunction
public static void error(final Context cx, final Scriptable thisObj,
    final Object[] args, final Function funObj) {
    final WebConsole webConsole = toWebConsole(thisObj);
    final Formatter oldFormatter = webConsole.getFormatter();
    webConsole.setFormatter(FORMATTER_);
    webConsole.error(args);
    webConsole.setFormatter(oldFormatter);
}
 
Example #26
Source File: Promise.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
private static Promise create(final Scriptable thisObj, final Object[] args, final PromiseState state) {
    // fulfilled promises are returned
    if (args.length != 0 && args[0] instanceof Promise && state == PromiseState.FULFILLED) {
        return (Promise) args[0];
    }

    final Promise promise;
    if (args.length > 0) {
        final Object arg = args[0];
        if (arg instanceof NativeObject) {
            final NativeObject nativeObject = (NativeObject) arg;
            promise = new Promise(nativeObject.get("then", nativeObject));
        }
        else {
            promise = new Promise();
            promise.value_ = arg;
            promise.state_ = state;
        }
    }
    else {
        promise = new Promise();
        promise.value_ = Undefined.instance;
        promise.state_ = state;
    }

    promise.setParentScope(thisObj.getParentScope());
    promise.setPrototype(getWindow(thisObj).getPrototype(promise.getClass()));
    return promise;
}
 
Example #27
Source File: NamespaceCollection.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public Object get(final String name, final Scriptable start) {
    for (final Namespace n : namespaces_) {
        if (StringUtils.equals(n.getName(), name)) {
            return n;
        }
    }
    return super.get(name, start);
}
 
Example #28
Source File: XMLHTTPRequest.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Object get(String name, final Scriptable start) {
    for (final String property : ALL_PROPERTIES_) {
        if (property.equalsIgnoreCase(name)) {
            name = property;
            break;
        }
    }
    return super.get(name, start);
}
 
Example #29
Source File: HtmlUnitContextFactory.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected Object doTopCall(final Callable callable,
        final Context cx, final Scriptable scope,
        final Scriptable thisObj, final Object[] args) {

    final TimeoutContext tcx = (TimeoutContext) cx;
    tcx.startClock();
    return super.doTopCall(callable, cx, scope, thisObj, args);
}
 
Example #30
Source File: FileList.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void setParentScope(final Scriptable m) {
    super.setParentScope(m);
    if (files_ != null) {
        for (final File file : files_) {
            file.setParentScope(m);
            file.setPrototype(getPrototype(file.getClass()));
        }
    }
}