Java Code Examples for com.gargoylesoftware.htmlunit.BrowserVersion#hasFeature()

The following examples show how to use com.gargoylesoftware.htmlunit.BrowserVersion#hasFeature() . 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: CSSFontFaceRule.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public String getCssText() {
    String cssText = super.getCssText();
    final BrowserVersion browserVersion = getBrowserVersion();
    if (browserVersion.hasFeature(CSS_FONTFACERULE_CSSTEXT_CRLF)) {
        cssText = StringUtils.replace(cssText, "{", "{\r\n\t");
        cssText = StringUtils.replace(cssText, "}", ";\r\n}\r\n");
        cssText = StringUtils.replace(cssText, "; ", ";\r\n\t");
    }
    else if (browserVersion.hasFeature(CSS_FONTFACERULE_CSSTEXT_NO_CRLF)) {
        cssText = StringUtils.replace(cssText, "{", "{ ");
        cssText = StringUtils.replace(cssText, "}", "; }");
        cssText = StringUtils.replace(cssText, "; ", "; ");
        cssText = REPLACEMENT_1.matcher(cssText).replaceFirst("font-family: $1;");
        cssText = REPLACEMENT_2.matcher(cssText).replaceFirst("src: url(\"$1\");");
    }
    else {
        cssText = StringUtils.replace(cssText, "{", "{\n  ");
        cssText = StringUtils.replace(cssText, "}", ";\n}");
        cssText = StringUtils.replace(cssText, "; ", ";\n  ");
        cssText = REPLACEMENT_1.matcher(cssText).replaceFirst("font-family: \"$1\";");
        cssText = REPLACEMENT_2.matcher(cssText).replaceFirst("src: url(\"$1\");");
    }
    return cssText;
}
 
Example 2
Source File: HTMLOptionsCollection.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Removes the option at the specified index.
 * @param index the option index
 */
@JsxFunction
public void remove(final int index) {
    int idx = index;
    final BrowserVersion browser = getBrowserVersion();
    if (idx < 0) {
        if (browser.hasFeature(JS_SELECT_OPTIONS_REMOVE_IGNORE_IF_INDEX_NEGATIVE)) {
            return;
        }
        if (index < 0 && getBrowserVersion().hasFeature(JS_SELECT_OPTIONS_REMOVE_THROWS_IF_NEGATIV)) {
            throw Context.reportRuntimeError("Invalid index for option collection: " + index);
        }
    }

    idx = Math.max(idx, 0);
    if (idx >= getLength()) {
        if (browser.hasFeature(JS_SELECT_OPTIONS_REMOVE_IGNORE_IF_INDEX_TOO_LARGE)) {
            return;
        }
        idx = 0;
    }
    htmlSelect_.removeOption(idx);
}
 
Example 3
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 4
Source File: HtmlResetInput.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Add missing attribute if needed by fixing attribute map rather to add it afterwards as this second option
 * triggers the instantiation of the script object at a time where the DOM node has not yet been added to its
 * parent.
 */
private static Map<String, DomAttr> addValueIfNeeded(final SgmlPage page,
        final Map<String, DomAttr> attributes) {

    final BrowserVersion browserVersion = page.getWebClient().getBrowserVersion();
    if (browserVersion.hasFeature(RESETINPUT_DEFAULT_VALUE_IF_VALUE_NOT_DEFINED)) {
        for (final String key : attributes.keySet()) {
            if ("value".equalsIgnoreCase(key)) {
                return attributes; // value attribute was specified
            }
        }

        // value attribute was not specified, add it
        final DomAttr newAttr = new DomAttr(page, null, "value", DEFAULT_VALUE, true);
        attributes.put("value", newAttr);
    }

    return attributes;
}
 
Example 5
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 "time" portion using the current 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 toLocaleTimeString(
        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 = "\u200Eh\u200E:\u200Emm\u200E:\u200Ess\u200E \u200Ea";
    }
    else {
        formatString = "h:mm:ss a";
    }
    final FastDateFormat format =  FastDateFormat.getInstance(formatString, getLocale(browserVersion));
    return format.format(getDateValue(thisObj));
}
 
Example 6
Source File: HtmlSubmitInput.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Add missing attribute if needed by fixing attribute map rather to add it afterwards as this second option
 * triggers the instantiation of the script object at a time where the DOM node has not yet been added to its
 * parent.
 */
private static Map<String, DomAttr> addValueIfNeeded(final SgmlPage page,
        final Map<String, DomAttr> attributes) {

    final BrowserVersion browserVersion = page.getWebClient().getBrowserVersion();
    if (browserVersion.hasFeature(SUBMITINPUT_DEFAULT_VALUE_IF_VALUE_NOT_DEFINED)) {
        for (final String key : attributes.keySet()) {
            if ("value".equalsIgnoreCase(key)) {
                return attributes; // value attribute was specified
            }
        }

        // value attribute was not specified, add it
        final DomAttr newAttr = new DomAttr(page, null, "value", DEFAULT_VALUE, true);
        attributes.put("value", newAttr);
    }

    return attributes;
}
 
Example 7
Source File: HTMLParser.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Create the configuration depending on the simulated browser
 * @param webClient the current WebClient
 * @return the configuration
 */
private static XMLParserConfiguration createConfiguration(final BrowserVersion browserVersion) {
    final HTMLConfiguration configuration = new HTMLConfiguration();
    if (browserVersion.hasFeature(HTML_COMMAND_TAG)) {
        configuration.htmlElements_.setElement(new HTMLElements.Element(HTMLElements.COMMAND, "COMMAND",
                HTMLElements.Element.EMPTY, HTMLElements.BODY, null));
    }
    if (browserVersion.hasFeature(HTML_ISINDEX_TAG)) {
        configuration.htmlElements_.setElement(new HTMLElements.Element(HTMLElements.ISINDEX, "ISINDEX",
                HTMLElements.Element.INLINE, HTMLElements.BODY, null));
    }
    if (browserVersion.hasFeature(HTML_MAIN_TAG)) {
        configuration.htmlElements_.setElement(new HTMLElements.Element(HTMLElements.MAIN, "MAIN",
                HTMLElements.Element.INLINE, HTMLElements.BODY, null));
    }

    return configuration;
}
 
Example 8
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 9
Source File: HTMLFormElement.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the value of the property {@code action}.
 * @return the value of this property
 */
@JsxGetter
public String getAction() {
    String action = getHtmlForm().getActionAttribute();
    final BrowserVersion browser = getBrowserVersion();
    if (action != DomElement.ATTRIBUTE_NOT_DEFINED) {
        if (action.length() == 0 && browser.hasFeature(JS_FORM_ACTION_EXPANDURL_IGNORE_EMPTY)) {
            return action;
        }

        try {
            action = ((HtmlPage) getHtmlForm().getPage()).getFullyQualifiedUrl(action).toExternalForm();
        }
        catch (final MalformedURLException e) {
            // nothing, return action attribute
        }
    }
    return action;
}
 
Example 10
Source File: ComputedCSSStyleDeclaration.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Makes a local, "computed", modification to this CSS style.
 *
 * @param declaration the style declaration
 * @param selector the selector determining that the style applies to this element
 */
public void applyStyleFromSelector(final org.w3c.dom.css.CSSStyleDeclaration declaration, final Selector selector) {
    final BrowserVersion browserVersion = getBrowserVersion();
    final SelectorSpecificity specificity = selector.getSelectorSpecificity();
    for (int i = 0; i < declaration.getLength(); i++) {
        final String name = declaration.item(i);
        if (!browserVersion.hasFeature(CSS_COMPUTED_NO_Z_INDEX) || !"z-index".equals(name)) {
            final String value = declaration.getPropertyValue(name);
            final String priority = declaration.getPropertyPriority(name);
            applyLocalStyleAttribute(name, value, priority, specificity);
        }
    }
}
 
Example 11
Source File: AbstractList.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}.
 */
@Override
public Object[] getIds() {
    // let's Rhino work normally if current instance is the prototype
    if (isPrototype()) {
        return super.getIds();
    }

    final List<String> idList = new ArrayList<>();
    final List<DomNode> elements = getElements();

    final BrowserVersion browserVersion = getBrowserVersion();
    if (browserVersion.hasFeature(JS_NODE_LIST_ENUMERATE_FUNCTIONS)) {
        final int length = elements.size();
        for (int i = 0; i < length; i++) {
            idList.add(Integer.toString(i));
        }

        idList.add("length");
        final JavaScriptConfiguration jsConfig = getWindow().getWebWindow().getWebClient()
            .getJavaScriptEngine().getJavaScriptConfiguration();
        for (final String name : jsConfig.getClassConfiguration(getClassName()).getFunctionKeys()) {
            idList.add(name);
        }
    }
    else {
        idList.add("length");
    }
    if (browserVersion.hasFeature(JS_NODE_LIST_ENUMERATE_CHILDREN)) {
        addElementIds(idList, elements);
    }

    return idList.toArray();
}
 
Example 12
Source File: BeforeUnloadEvent.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
private static Object getReturnValueDefault(final BrowserVersion browserVersion) {
    if (browserVersion.hasFeature(EVENT_BEFORE_UNLOAD_RETURN_VALUE_IS_HTML5_LIKE)) {
        // Empty string default is specified by HTML5
        // https://www.w3.org/TR/html5/browsers.html#the-beforeunloadevent-interface
        return "";
    }
    return Undefined.instance;
}
 
Example 13
Source File: MediaList.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
@Override
public Object getDefaultValue(final Class<?> hint) {
    if (getPrototype() != null) {
        final BrowserVersion browserVersion = getBrowserVersion();
        if (browserVersion.hasFeature(JS_MEDIA_LIST_EMPTY_STRING)) {
            return "";
        }
        if (browserVersion.hasFeature(JS_MEDIA_LIST_ALL)) {
            return "all";
        }
    }
    return super.getDefaultValue(hint);
}
 
Example 14
Source File: XMLHttpRequest.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
private boolean isAllowCrossDomainsFor(final URL newUrl) {
    final BrowserVersion browser = getBrowserVersion();
    if (browser.hasFeature(XHR_NO_CROSS_ORIGIN_TO_ABOUT)
            && "about".equals(newUrl.getProtocol())) {
        return false;
    }

    return true;
}
 
Example 15
Source File: FileReader.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Reads the contents of the specified {@link Blob} or {@link File}.
 * @param object the {@link Blob} or {@link File} from which to read
 * @throws IOException if an error occurs
 */
@JsxFunction
public void readAsDataURL(final Object object) throws IOException {
    readyState_ = LOADING;
    final java.io.File file = ((File) object).getFile();
    String contentType = Files.probeContentType(file.toPath());
    try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
        FileUtils.copyFile(file, bos);

        final byte[] bytes = bos.toByteArray();
        final String value = new String(new Base64().encode(bytes));
        final BrowserVersion browserVersion = getBrowserVersion();

        result_ = "data:";
        final boolean includeConentType = browserVersion.hasFeature(JS_FILEREADER_CONTENT_TYPE);
        if (!value.isEmpty() || includeConentType) {
            if (contentType == null) {
                if (includeConentType) {
                    contentType = "application/octet-stream";
                }
                else {
                    contentType = "";
                }
            }
            result_ += contentType + ";base64," + value;
        }
        if (value.isEmpty() && getBrowserVersion().hasFeature(JS_FILEREADER_EMPTY_NULL)) {
            result_ = "null";
        }
    }
    readyState_ = DONE;

    final Event event = new Event(this, Event.TYPE_LOAD);
    fireEvent(event);
}
 
Example 16
Source File: HtmlImage.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * <p>Downloads the image contained by this image element.</p>
 * <p><span style="color:red">POTENTIAL PERFORMANCE KILLER - DOWNLOADS THE IMAGE - USE AT YOUR OWN RISK</span></p>
 * <p>If the image has not already been downloaded, this method triggers a download and caches the image.</p>
 *
 * @throws IOException if an error occurs while downloading the image
 */
private void downloadImageIfNeeded() throws IOException {
    if (!downloaded_) {
        // HTMLIMAGE_BLANK_SRC_AS_EMPTY
        final String src = getSrcAttribute();

        if (!"".equals(src)) {
            final HtmlPage page = (HtmlPage) getPage();
            final WebClient webClient = page.getWebClient();
            final BrowserVersion browser = webClient.getBrowserVersion();

            if (!(browser.hasFeature(HTMLIMAGE_BLANK_SRC_AS_EMPTY)
                    && StringUtils.isBlank(src))) {
                final URL url = page.getFullyQualifiedUrl(src);
                final WebRequest request = new WebRequest(url, browser.getImgAcceptHeader(),
                                                                browser.getAcceptEncodingHeader());
                request.setCharset(page.getCharset());
                request.setAdditionalHeader(HttpHeader.REFERER, page.getUrl().toExternalForm());
                imageWebResponse_ = webClient.loadWebResponse(request);
            }
        }

        if (imageData_ != null) {
            imageData_.close();
            imageData_ = null;
        }
        downloaded_ = true;
        isComplete_ = hasFeature(JS_IMAGE_COMPLETE_RETURNS_TRUE_FOR_NO_REQUEST)
                || (imageWebResponse_ != null && imageWebResponse_.getContentType().contains("image"));

        width_ = -1;
        height_ = -1;
    }
}
 
Example 17
Source File: ComputedCSSStyleDeclaration.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Makes a local, "computed", modification to this CSS style.
 *
 * @param declaration the style declaration
 * @param selector the selector determining that the style applies to this element
 */
public void applyStyleFromSelector(final CSSStyleDeclarationImpl declaration, final Selector selector) {
    final BrowserVersion browserVersion = getBrowserVersion();
    final SelectorSpecificity specificity = selector.getSelectorSpecificity();
    for (Property prop : declaration.getProperties()) {
        final String name = prop.getName();
        if (!browserVersion.hasFeature(CSS_COMPUTED_NO_Z_INDEX) || !"z-index".equals(name)) {
            final String value = declaration.getPropertyValue(name);
            final String priority = declaration.getPropertyPriority(name);
            applyLocalStyleAttribute(name, value, priority, specificity);
        }
    }
}
 
Example 18
Source File: HTMLInputElement.java    From htmlunit with Apache License 2.0 4 votes vote down vote up
/**
 * Sets the value of the attribute {@code type}.
 * Note: this replace the DOM node with a new one.
 * @param newType the new type to set
 */
@JsxSetter
public void setType(String newType) {
    HtmlInput input = getDomNodeOrDie();

    final String currentType = input.getAttributeDirect("type");

    final BrowserVersion browser = getBrowserVersion();
    if (!currentType.equalsIgnoreCase(newType)) {
        if (newType != null && browser.hasFeature(JS_INPUT_SET_TYPE_LOWERCASE)) {
            newType = newType.toLowerCase(Locale.ROOT);
        }

        if (!browser.hasFeature(HTMLINPUT_TYPE_DATETIME_SUPPORTED)
                && ("week".equals(newType)
                        || "month".equals(newType)
                        || "date".equals(newType)
                        || "datetime-local".equals(newType)
                        || "time".equals(newType))) {
            throw Context.reportRuntimeError("Invalid argument '" + newType + "' for setting property type.");
        }

        if (browser.hasFeature(HTMLINPUT_TYPE_COLOR_NOT_SUPPORTED)
                && "color".equals(newType)) {
            throw Context.reportRuntimeError("Invalid argument '" + newType + "' for setting property type.");
        }

        final AttributesImpl attributes = readAttributes(input);
        final int index = attributes.getIndex("type");
        if (index > -1) {
            attributes.setValue(index, newType);
        }
        else {
            attributes.addAttribute(null, "type", "type", null, newType);
        }

        // create a new one only if we have a new type
        if (ATTRIBUTE_NOT_DEFINED != currentType || !"text".equalsIgnoreCase(newType)) {
            final SgmlPage page = input.getPage();
            final HtmlInput newInput = (HtmlInput) page.getWebClient().getPageCreator().getHtmlParser()
                    .getFactory(HtmlInput.TAG_NAME)
                    .createElement(page, HtmlInput.TAG_NAME, attributes);

            if (input.wasCreatedByJavascript()) {
                newInput.markAsCreatedByJavascript();
            }

            if (input.getParentNode() == null) {
                // the input hasn't yet been inserted into the DOM tree (likely has been
                // created via document.createElement()), so simply replace it with the
                // new Input instance created in the code above
                input = newInput;
            }
            else {
                input.getParentNode().replaceChild(newInput, input);
            }

            input.setScriptableObject(null);
            setDomNode(newInput, true);
        }
        else {
            super.setAttribute("type", newType);
        }
    }
}
 
Example 19
Source File: ComputedCSSStyleDeclaration.java    From HtmlUnit-Android with Apache License 2.0 4 votes vote down vote up
/**
 * Returns the {@code display} attribute.
 * @param ignoreBlockIfNotAttached is
 * {@link com.gargoylesoftware.htmlunit.BrowserVersionFeatures#CSS_COMPUTED_BLOCK_IF_NOT_ATTACHED} ignored
 * @return the {@code display} attribute
 */
public String getDisplay(final boolean ignoreBlockIfNotAttached) {
    // don't use defaultIfEmpty for performance
    // (no need to calculate the default if not empty)
    final Element elem = getElement();
    final DomElement domElem = elem.getDomNodeOrDie();
    boolean changeValueIfEmpty = false;
    if (!domElem.isAttachedToPage()) {
        final BrowserVersion browserVersion = getBrowserVersion();
        if (browserVersion.hasFeature(CSS_COMPUTED_NO_Z_INDEX)) {
            return "";
        }
        if (!ignoreBlockIfNotAttached && browserVersion.hasFeature(CSS_COMPUTED_BLOCK_IF_NOT_ATTACHED)) {
            changeValueIfEmpty = true;
        }
    }
    final String value = super.getStyleAttribute(DISPLAY, false);
    if (StringUtils.isEmpty(value)) {
        if (domElem instanceof HtmlElement) {
            final String defaultValue = ((HtmlElement) domElem).getDefaultStyleDisplay().value();
            if (changeValueIfEmpty) {
                switch (defaultValue) {
                    case "inline":
                    case "inline-block":
                    case "table-caption":
                    case "table-cell":
                    case "table-column":
                    case "table-column-group":
                    case "table-footer-group":
                    case "table-header-group":
                    case "table-row":
                    case "table-row-group":
                    case "list-item":
                    case "ruby":
                        return "block";

                    default:
                }
            }
            return defaultValue;
        }
        return "";
    }
    return value;
}
 
Example 20
Source File: HtmlForm.java    From HtmlUnit-Android with Apache License 2.0 4 votes vote down vote up
/**
 * Check if element which cause submit contains new html5 attributes
 * (formaction, formmethod, formtarget, formenctype)
 * and override existing values
 * @param submitElement
 */
private void updateHtml5Attributes(final SubmittableElement submitElement) {
    if (submitElement instanceof HtmlElement) {
        final HtmlElement element = (HtmlElement) submitElement;

        final String type = element.getAttributeDirect("type");
        boolean typeImage = false;
        final boolean typeSubmit = "submit".equalsIgnoreCase(type);
        final boolean isInput = HtmlInput.TAG_NAME.equals(element.getTagName());
        if (isInput) {
            typeImage = "image".equalsIgnoreCase(type);
        }

        // IE does not support formxxx attributes for input with 'image' types
        final BrowserVersion browser = getPage().getWebClient().getBrowserVersion();
        if (browser.hasFeature(FORM_PARAMETRS_NOT_SUPPORTED_FOR_IMAGE) && typeImage) {
            return;
        }

        // could be excessive validation but support of html5 fromxxx
        // attributes available for:
        // - input with 'submit' and 'image' types
        // - button with 'submit'
        if (isInput && !typeSubmit && !typeImage) {
            return;
        }
        else if (HtmlButton.TAG_NAME.equals(element.getTagName())
            && !"submit".equalsIgnoreCase(type)) {
            return;
        }

        final String formaction = element.getAttributeDirect("formaction");
        if (DomElement.ATTRIBUTE_NOT_DEFINED != formaction) {
            setActionAttribute(formaction);
        }
        final String formmethod = element.getAttributeDirect("formmethod");
        if (DomElement.ATTRIBUTE_NOT_DEFINED != formmethod) {
            setMethodAttribute(formmethod);
        }
        final String formtarget = element.getAttributeDirect("formtarget");
        if (DomElement.ATTRIBUTE_NOT_DEFINED != formtarget) {
            setTargetAttribute(formtarget);
        }
        final String formenctype = element.getAttributeDirect("formenctype");
        if (DomElement.ATTRIBUTE_NOT_DEFINED != formenctype) {
            setEnctypeAttribute(formenctype);
        }
    }
}