Java Code Examples for net.sourceforge.htmlunit.corejs.javascript.Context#toString()

The following examples show how to use net.sourceforge.htmlunit.corejs.javascript.Context#toString() . 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: HTMLInputElement.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Sets the value of the JavaScript attribute {@code value}.
 *
 * @param newValue the new value
 */
@Override
public void setValue(final Object newValue) {
    if (null == newValue) {
        getDomNodeOrDie().setValueAttribute("");
        return;
    }

    final String val = Context.toString(newValue);
    final BrowserVersion browserVersion = getBrowserVersion();
    if (StringUtils.isNotEmpty(val) && "file".equalsIgnoreCase(getType())) {
        if (browserVersion.hasFeature(JS_SELECT_FILE_THROWS)) {
            throw Context.reportRuntimeError("InvalidStateError: "
                    + "Failed to set the 'value' property on 'HTMLInputElement'.");
        }
        return;
    }

    getDomNodeOrDie().setValueAttribute(val);
}
 
Example 2
Source File: Symbol.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
@JsxFunction
public String toString() {
    String name;
    if (name_ == Undefined.instance) {
        name = "";
    }
    else {
        name = Context.toString(name_);
        final ClassConfiguration config = AbstractJavaScriptConfiguration
                .getClassConfiguration(getClass(), getBrowserVersion());

        for (final Entry<String, ClassConfiguration.PropertyInfo> propertyEntry
                : config.getStaticPropertyEntries()) {
            if (propertyEntry.getKey().equals(name)) {
                name = "Symbol." + name;
                break;
            }
        }
    }
    return "Symbol(" + name + ')';
}
 
Example 3
Source File: PopStateEvent.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new event instance.
 *
 * @param target the event target
 * @param type the event type
 * @param state the state object
 */
public PopStateEvent(final EventTarget target, final String type, final Object state) {
    super(target, type);
    if (state instanceof NativeObject && getBrowserVersion().hasFeature(JS_POP_STATE_EVENT_CLONE_STATE)) {
        final NativeObject old = (NativeObject) state;
        final NativeObject newState = new NativeObject();
        Context.enter();
        try {
            for (final Object o : ScriptableObject.getPropertyIds(old)) {
                final String property = Context.toString(o);
                newState.defineProperty(property, ScriptableObject.getProperty(old, property),
                        ScriptableObject.EMPTY);
            }
        }
        finally {
            Context.exit();
        }
        state_ = newState;
    }
    else {
        state_ = state;
    }
}
 
Example 4
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 5
Source File: Element.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Replaces all child elements of this element with the supplied value.
 * @param value the new value for the contents of this element
 */
@JsxSetter({CHROME, FF, FF68, FF60})
public void setInnerHTML(final Object value) {
    final DomNode domNode;
    try {
        domNode = getDomNodeOrDie();
    }
    catch (final IllegalStateException e) {
        Context.throwAsScriptRuntimeEx(e);
        return;
    }

    domNode.removeAllChildren();
    getWindow().clearComputedStylesUpToRoot(this);

    final boolean addChildForNull = getBrowserVersion().hasFeature(JS_INNER_HTML_ADD_CHILD_FOR_NULL_VALUE);
    if ((value == null && addChildForNull) || (value != null && !"".equals(value))) {
        final String valueAsString = Context.toString(value);
        parseHtmlSnippet(domNode, valueAsString);
    }
}
 
Example 6
Source File: Window.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * The JavaScript function {@code prompt}.
 * @param message the message
 * @param defaultValue the default value displayed in the text input field
 * @return the value typed in or {@code null} if the user pressed {@code cancel}
 */
@JsxFunction
public String prompt(final String message, Object defaultValue) {
    final PromptHandler handler = getWebWindow().getWebClient().getPromptHandler();
    if (handler == null) {
        if (LOG.isWarnEnabled()) {
            LOG.warn("window.prompt(\"" + message + "\") no prompt handler installed");
        }
        return null;
    }
    if (Undefined.isUndefined(defaultValue)) {
        defaultValue = null;
    }
    else {
        defaultValue = Context.toString(defaultValue);
    }
    return handler.handlePrompt(document_.getPage(), message, (String) defaultValue);
}
 
Example 7
Source File: Window.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * The JavaScript function {@code alert()}.
 * @param message the message
 */
@JsxFunction
public void alert(final Object message) {
    // use Object as parameter and perform String conversion by ourself
    // this allows to place breakpoint here and "see" the message object and its properties
    final String stringMessage = Context.toString(message);
    final AlertHandler handler = getWebWindow().getWebClient().getAlertHandler();
    if (handler == null) {
        if (LOG.isWarnEnabled()) {
            LOG.warn("window.alert(\"" + stringMessage + "\") no alert handler installed");
        }
    }
    else {
        handler.handleAlert(document_.getPage(), stringMessage);
    }
}
 
Example 8
Source File: CSSStyleDeclaration.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
@Override
public void put(final String name, final Scriptable start, final Object value) {
    if (this != start) {
        super.put(name, start, value);
        return;
    }

    final Scriptable prototype = getPrototype();
    if (prototype != null && !"constructor".equals(name) && prototype.get(name, start) != Scriptable.NOT_FOUND) {
        prototype.put(name, start, value);
        return;
    }

    if (getDomNodeOrNull() != null) { // check if prototype or not
        final Definition style = StyleAttributes.getDefinition(name, getBrowserVersion());
        if (style != null) {
            final String stringValue = Context.toString(value);
            setStyleAttribute(style.getAttributeName(), stringValue);
            return;
        }
    }

    super.put(name, start, value);
}
 
Example 9
Source File: HTMLElement.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Sets the value of the {@code vAlign} property.
 * @param vAlign the value of the {@code vAlign} property
 * @param valid the valid values; if {@code null}, any value is valid
 */
protected void setVAlign(final Object vAlign, final String[] valid) {
    final String valign = Context.toString(vAlign);
    final String valignLC = valign.toLowerCase(Locale.ROOT);
    if (valid == null || ArrayUtils.contains(valid, valignLC)) {
        if (getBrowserVersion().hasFeature(JS_VALIGN_CONVERTS_TO_LOWERCASE)) {
            getDomNodeOrDie().setAttribute("valign", valignLC);
        }
        else {
            getDomNodeOrDie().setAttribute("valign", valign);
        }
    }
    else {
        throw Context.reportRuntimeError("Cannot set the vAlign property to invalid value: " + vAlign);
    }
}
 
Example 10
Source File: DedicatedWorkerGlobalScope.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
void messagePosted(final Object message) {
    final MessageEvent event = new MessageEvent();
    event.initMessageEvent(Event.TYPE_MESSAGE, false, false, message, origin_, "", owningWindow_, null);
    event.setParentScope(owningWindow_);
    event.setPrototype(owningWindow_.getPrototype(event.getClass()));

    final JavaScriptEngine jsEngine =
            (JavaScriptEngine) owningWindow_.getWebWindow().getWebClient().getJavaScriptEngine();
    final ContextAction action = new ContextAction() {
        @Override
        public Object run(final Context cx) {
            return executeEvent(cx, event);
        }
    };

    final ContextFactory cf = jsEngine.getContextFactory();

    final JavaScriptJob job = new WorkerJob(cf, action, "messagePosted: " + Context.toString(message));

    final HtmlPage page = (HtmlPage) owningWindow_.getDocument().getPage();
    owningWindow_.getWebWindow().getJobManager().addJob(job, page);
}
 
Example 11
Source File: DedicatedWorkerGlobalScope.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Posts a message to the {@link Worker} in the page's context.
 * @param message the message
 */
@JsxFunction
public void postMessage(final Object message) {
    final MessageEvent event = new MessageEvent();
    event.initMessageEvent(Event.TYPE_MESSAGE, false, false, message, origin_, "",
                                owningWindow_, Undefined.instance);
    event.setParentScope(owningWindow_);
    event.setPrototype(owningWindow_.getPrototype(event.getClass()));

    if (LOG.isDebugEnabled()) {
        LOG.debug("[DedicatedWorker] postMessage: {}" + message);
    }
    final JavaScriptEngine jsEngine =
            (JavaScriptEngine) owningWindow_.getWebWindow().getWebClient().getJavaScriptEngine();
    final ContextAction<Object> action = new ContextAction<Object>() {
        @Override
        public Object run(final Context cx) {
            worker_.getEventListenersContainer().executeCapturingListeners(event, null);
            final Object[] args = {event};
            worker_.getEventListenersContainer().executeBubblingListeners(event, args);
            return null;
        }
    };

    final ContextFactory cf = jsEngine.getContextFactory();

    final JavaScriptJob job = new WorkerJob(cf, action, "postMessage: " + Context.toString(message));

    final HtmlPage page = (HtmlPage) owningWindow_.getDocument().getPage();
    owningWindow_.getWebWindow().getJobManager().addJob(job, page);
}
 
Example 12
Source File: HTMLElement.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Replaces all child elements of this element with the supplied text value.
 * @param value the new value for the contents of this element
 */
@JsxSetter
public void setInnerText(final Object value) {
    final String valueString;
    if (value == null && getBrowserVersion().hasFeature(JS_INNER_TEXT_VALUE_NULL)) {
        valueString = null;
    }
    else {
        valueString = Context.toString(value);
    }
    setInnerTextImpl(valueString);
}
 
Example 13
Source File: HTMLFormElement.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves a form object or an object from an elements collection.
 * @param index Integer or String that specifies the object or collection to retrieve.
 *              If this parameter is an integer, it is the zero-based index of the object.
 *              If this parameter is a string, all objects with matching name or id properties are retrieved,
 *              and a collection is returned if more than one match is made
 * @param subIndex Optional. Integer that specifies the zero-based index of the object to retrieve
 *              when a collection is returned
 * @return an object or a collection of objects if successful, or null otherwise
 */
@JsxFunction(IE)
public Object item(final Object index, final Object subIndex) {
    if (index instanceof Number) {
        return getElements().item(index);
    }

    final String name = Context.toString(index);
    final Object response = getWithPreemption(name);
    if (subIndex instanceof Number && response instanceof HTMLCollection) {
        return ((HTMLCollection) response).item(subIndex);
    }

    return response;
}
 
Example 14
Source File: CSSStyleDeclaration.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the {@code opacity} style attribute.
 * @param opacity the new attribute
 */
@JsxSetter
public void setOpacity(final Object opacity) {
    if (ScriptRuntime.isNaN(opacity)) {
        return;
    }

    final double doubleValue;
    if (opacity instanceof Number) {
        doubleValue = ((Number) opacity).doubleValue();
    }
    else {
        String valueString = Context.toString(opacity);

        if (valueString.isEmpty()) {
            setStyleAttribute(OPACITY.getAttributeName(), valueString);
            return;
        }

        valueString = valueString.trim();
        try {
            doubleValue = Double.parseDouble(valueString);
        }
        catch (final NumberFormatException e) {
            // ignore wrong value
            return;
        }
    }

    if (Double.isNaN(doubleValue) || Double.isInfinite(doubleValue)) {
        return;
    }
    setStyleAttribute(OPACITY.getAttributeName(), Double.toString(doubleValue));
}
 
Example 15
Source File: Window.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * The JavaScript function {@code alert()}.
 * @param message the message
 */
@JsxFunction
public void alert(final Object message) {
    // use Object as parameter and perform String conversion by ourself
    // this allows to place breakpoint here and "see" the message object and its properties
    final String stringMessage = Context.toString(message);
    final AlertHandler handler = getWebWindow().getWebClient().getAlertHandler();
    if (handler == null) {
        LOG.warn("window.alert(\"" + stringMessage + "\") no alert handler installed");
    }
    else {
        handler.handleAlert(document_.getPage(), stringMessage);
    }
}
 
Example 16
Source File: ComputedCSSStyleDeclaration.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public String getPropertyValue(final String name) {
    // need to invoke the getter to take care of the default value
    final Object property = getProperty(this, camelize(name));
    if (property == NOT_FOUND) {
        return super.getPropertyValue(name);
    }
    return Context.toString(property);
}
 
Example 17
Source File: Worker.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * For instantiation in JavaScript.
 * @param cx the current context
 * @param args the URIs
 * @param ctorObj the function object
 * @param inNewExpr Is new or not
 * @return the java object to allow JavaScript to access
 * @throws Exception in case of problem
 */
@JsxConstructor
public static Scriptable jsConstructor(
        final Context cx, final Object[] args, final Function ctorObj,
        final boolean inNewExpr) throws Exception {
    if (args.length < 1 || args.length > 2) {
        throw Context.reportRuntimeError(
                "Worker Error: constructor must have one or two String parameters.");
    }

    final String url = Context.toString(args[0]);

    return new Worker(cx, getWindow(ctorObj), url);
}
 
Example 18
Source File: CSSStyleDeclaration.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the {@code opacity} style attribute.
 * @param opacity the new attribute
 */
@JsxSetter
public void setOpacity(final Object opacity) {
    if (ScriptRuntime.NaNobj == opacity) {
        return;
    }

    final double doubleValue;
    if (opacity instanceof Number) {
        doubleValue = ((Number) opacity).doubleValue();
    }
    else {
        String valueString = Context.toString(opacity);

        if (valueString.isEmpty()) {
            setStyleAttribute(OPACITY.getAttributeName(), valueString);
            return;
        }

        valueString = valueString.trim();
        try {
            doubleValue = Double.parseDouble(valueString);
        }
        catch (final NumberFormatException e) {
            // ignore wrong value
            return;
        }
    }

    if (Double.isNaN(doubleValue) || Double.isInfinite(doubleValue)) {
        return;
    }
    setStyleAttribute(OPACITY.getAttributeName(), Double.toString(doubleValue));
}
 
Example 19
Source File: Worker.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * For instantiation in JavaScript.
 * @param cx the current context
 * @param args the URIs
 * @param ctorObj the function object
 * @param inNewExpr Is new or not
 * @return the java object to allow JavaScript to access
 * @throws Exception in case of problem
 */
@JsxConstructor
public static Scriptable jsConstructor(
        final Context cx, final Object[] args, final Function ctorObj,
        final boolean inNewExpr) throws Exception {
    if (args.length < 1 || args.length > 2) {
        throw Context.reportRuntimeError(
                "Worker Error: constructor must have one or two String parameters.");
    }

    final String url = Context.toString(args[0]);

    return new Worker(cx, getWindow(ctorObj), url);
}
 
Example 20
Source File: HTMLCanvasElement.java    From htmlunit with Apache License 2.0 4 votes vote down vote up
/**
 * Get the data: URL representation of the Canvas element.
 * Here we return an empty image.
 * @param type the type (optional)
 * @return the data URL
 */
@JsxFunction
public String toDataURL(final Object type) {
    if (context2d_ != null) {
        final String typeInUse;
        if (Undefined.isUndefined(type)) {
            typeInUse = null;
        }
        else {
            typeInUse = Context.toString(type);
        }
        return context2d_.toDataURL(typeInUse);
    }

    if (getBrowserVersion().hasFeature(JS_CANVAS_DATA_URL_IE_PNG)) {
        return "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASwAAACWCAYAAABkW7XSAAAAAXNSR0IArs4c6QAAAARnQU1BAA"
            + "Cxjwv8YQUAAADGSURBVHhe7cExAQAAAMKg9U9tCF8gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
            + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
            + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAONUAv9QAAcDhjokAAAAASUV"
            + "ORK5CYII=";
    }

    if (getBrowserVersion().hasFeature(JS_CANVAS_DATA_URL_CHROME_PNG)) {
        return "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASwAAACWCAYAAABkW7XSAAAEYklEQVR4Xu3UAQkAAAwCwdm/"
            + "9HI83BLIOdw5AgQIRAQWySkmAQIEzmB5AgIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYO"
            + "VqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1"
            + "OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamK"
            + "kEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWC"
            + "EiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCV"
            + "AwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgI"
            + "DB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg"
            + "+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbL"
            + "DxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8"
            + "gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QI"
            + "BARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAg"
            + "YyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZ"
            + "AYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgI"
            + "GK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDF"
            + "amKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlACBB1YxAJfjJb2jA"
            + "AAAAElFTkSuQmCC";
    }

    return "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASwAAACWCAYAAABkW7XSAAAAxUlEQVR4nO3BMQEAAADCoPVPbQhf"
        + "oAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
        + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
        + "AAAAAAAAAAAAAAAAAAAAAAAAAAAOA1v9QAATX68/0AAAAASUVORK5CYII=";
}