com.gargoylesoftware.htmlunit.html.HtmlImage Java Examples

The following examples show how to use com.gargoylesoftware.htmlunit.html.HtmlImage. 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: Window.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
private boolean matches(final Object object) {
    if (object instanceof HtmlEmbed
        || object instanceof HtmlForm
        || object instanceof HtmlImage
        || object instanceof HtmlObject) {
        return true;
    }

    return includeFormFields_
            && (object instanceof HtmlAnchor
                || object instanceof HtmlButton
                || object instanceof HtmlInput
                || object instanceof HtmlMap
                || object instanceof HtmlSelect
                || object instanceof HtmlTextArea);
}
 
Example #2
Source File: HTMLFormElement.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
private List<HtmlElement> findElements(final String name) {
    final List<HtmlElement> elements = new ArrayList<>();
    addElements(name, getHtmlForm().getHtmlElementDescendants(), elements);
    addElements(name, getHtmlForm().getLostChildren(), elements);

    // If no form fields are found, IE and Firefox are able to find img elements by ID or name.
    if (elements.isEmpty()) {
        for (final DomNode node : getHtmlForm().getChildren()) {
            if (node instanceof HtmlImage) {
                final HtmlImage img = (HtmlImage) node;
                if (name.equals(img.getId()) || name.equals(img.getNameAttribute())) {
                    elements.add(img);
                }
            }
        }
    }

    return elements;
}
 
Example #3
Source File: HTMLDocument.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
private List<DomNode> getItComputeElements(final HtmlPage page, final String name,
        final boolean forIDAndOrName, final boolean alsoFrames) {
    final List<DomElement> elements;
    if (forIDAndOrName) {
        elements = page.getElementsByIdAndOrName(name);
    }
    else {
        elements = page.getElementsByName(name);
    }
    final List<DomNode> matchingElements = new ArrayList<>();
    for (final DomElement elt : elements) {
        if (elt instanceof HtmlForm || elt instanceof HtmlImage
                || (alsoFrames && elt instanceof BaseFrameElement)) {
            matchingElements.add(elt);
        }
    }
    return matchingElements;
}
 
Example #4
Source File: HTMLImageElement.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the value of the {@code src} attribute.
 * @return the value of the {@code src} attribute
 */
@JsxGetter
public String getSrc() {
    final HtmlImage img = (HtmlImage) getDomNodeOrDie();
    final String src = img.getSrcAttribute();
    if ("".equals(src)) {
        return src;
    }
    try {
        final HtmlPage page = (HtmlPage) img.getPage();
        return page.getFullyQualifiedUrl(src).toExternalForm();
    }
    catch (final MalformedURLException e) {
        final String msg = "Unable to create fully qualified URL for src attribute of image " + e.getMessage();
        throw Context.reportRuntimeError(msg);
    }
}
 
Example #5
Source File: Document.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the value of the {@code embeds} property.
 * @return the value of the {@code embeds} property
 */
@JsxGetter({CHROME, IE})
public Object getImages() {
    return new HTMLCollection(getDomNodeOrDie(), false) {
        @Override
        protected boolean isMatching(final DomNode node) {
            return node instanceof HtmlImage;
        }

        @Override
        public Object call(final Context cx, final Scriptable scope,
                final Scriptable thisObj, final Object[] args) {
            if (getBrowserVersion().hasFeature(JS_DOCUMENT_FORMS_FUNCTION_SUPPORTED)) {
                return super.call(cx, scope, thisObj, args);
            }
            throw Context.reportRuntimeError("TypeError: document.images is not a function");
        }
    };
}
 
Example #6
Source File: Window.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
private boolean matches(final Object object) {
    if (object instanceof HtmlEmbed
        || object instanceof HtmlForm
        || object instanceof HtmlImage
        || object instanceof HtmlObject) {
        return true;
    }
    if (includeFormFields_ && (
            object instanceof HtmlAnchor
            || object instanceof HtmlButton
            || object instanceof HtmlInput
            || object instanceof HtmlMap
            || object instanceof HtmlSelect
            || object instanceof HtmlTextArea)) {
        return true;
    }
    return false;
}
 
Example #7
Source File: HTMLFormElement.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
private List<HtmlElement> findElements(final String name) {
    final List<HtmlElement> elements = new ArrayList<>();
    addElements(name, getHtmlForm().getHtmlElementDescendants(), elements);
    addElements(name, getHtmlForm().getLostChildren(), elements);

    // If no form fields are found, browsers are able to find img elements by ID or name.
    if (elements.isEmpty()) {
        for (final DomNode node : getHtmlForm().getHtmlElementDescendants()) {
            if (node instanceof HtmlImage) {
                final HtmlImage img = (HtmlImage) node;
                if (name.equals(img.getId()) || name.equals(img.getNameAttribute())) {
                    elements.add(img);
                }
            }
        }
    }

    return elements;
}
 
Example #8
Source File: HTMLDocument.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
private static List<DomNode> getItComputeElements(final HtmlPage page, final String name,
        final boolean forIDAndOrName, final boolean alsoFrames) {
    final List<DomElement> elements;
    if (forIDAndOrName) {
        elements = page.getElementsByIdAndOrName(name);
    }
    else {
        elements = page.getElementsByName(name);
    }
    final List<DomNode> matchingElements = new ArrayList<>();
    for (final DomElement elt : elements) {
        if (elt instanceof HtmlForm || elt instanceof HtmlImage || elt instanceof HtmlApplet
                || (alsoFrames && elt instanceof BaseFrameElement)) {
            matchingElements.add(elt);
        }
    }
    return matchingElements;
}
 
Example #9
Source File: HTMLImageElement.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the value of the {@code src} attribute.
 * @return the value of the {@code src} attribute
 */
@JsxGetter
public String getSrc() {
    final HtmlImage img = (HtmlImage) getDomNodeOrDie();
    final String src = img.getSrcAttribute();
    if ("".equals(src)) {
        return src;
    }
    try {
        final HtmlPage page = (HtmlPage) img.getPage();
        return page.getFullyQualifiedUrl(src).toExternalForm();
    }
    catch (final MalformedURLException e) {
        final String msg = "Unable to create fully qualified URL for src attribute of image " + e.getMessage();
        throw Context.reportRuntimeError(msg);
    }
}
 
Example #10
Source File: Document.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the value of the {@code embeds} property.
 * @return the value of the {@code embeds} property
 */
@JsxGetter({CHROME, IE})
public Object getImages() {
    return new HTMLCollection(getDomNodeOrDie(), false) {
        @Override
        protected boolean isMatching(final DomNode node) {
            return node instanceof HtmlImage;
        }

        @Override
        public Object call(final Context cx, final Scriptable scope,
                final Scriptable thisObj, final Object[] args) {
            if (getBrowserVersion().hasFeature(JS_DOCUMENT_FORMS_FUNCTION_SUPPORTED)) {
                return super.call(cx, scope, thisObj, args);
            }
            throw Context.reportRuntimeError("TypeError: document.images is not a function");
        }
    };
}
 
Example #11
Source File: HTMLImageElement.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * JavaScript constructor.
 */
@JsxConstructor({CHROME, FF, EDGE})
public void jsConstructor() {
    final SgmlPage page = (SgmlPage) getWindow().getWebWindow().getEnclosedPage();
    final DomElement fake =
            HTMLParser.getFactory(HtmlImage.TAG_NAME).createElement(page, HtmlImage.TAG_NAME, new AttributesImpl());
    setDomNode(fake);
}
 
Example #12
Source File: HudsonTestCase.java    From jenkins-test-harness with MIT License 5 votes vote down vote up
/**
 * Makes sure that all the images in the page loads successfully.
 * (By default, HtmlUnit doesn't load images.)
 */
public void assertAllImageLoadSuccessfully(HtmlPage p) {
    for (HtmlImage img : DomNodeUtil.<HtmlImage>selectNodes(p, "//IMG")) {
        try {
            assertEquals("Failed to load " + img.getSrcAttribute(),
                    200,
                    img.getWebResponse(true).getStatusCode());
        } catch (IOException e) {
            throw new AssertionError("Failed to load " + img.getSrcAttribute());
        }
    }
}
 
Example #13
Source File: JenkinsRule.java    From jenkins-test-harness with MIT License 5 votes vote down vote up
/**
 * Makes sure that all the images in the page loads successfully.
 * (By default, HtmlUnit doesn't load images.)
 */
public void assertAllImageLoadSuccessfully(HtmlPage p) {
    for (HtmlImage img : DomNodeUtil.<HtmlImage>selectNodes(p, "//IMG")) {
        try {
            assertEquals("Failed to load " + img.getSrcAttribute(),
                    200,
                    img.getWebResponse(true).getStatusCode());
        } catch (IOException e) {
            throw new AssertionError("Failed to load " + img.getSrcAttribute());
        }
    }
}
 
Example #14
Source File: CanvasRenderingContext2D.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Draws images onto the canvas.
 *
 * @param image an element to draw into the context
 * @param sx the X coordinate of the top left corner of the sub-rectangle of the source image
 *        to draw into the destination context
 * @param sy the Y coordinate of the top left corner of the sub-rectangle of the source image
 *        to draw into the destination context
 * @param sWidth the width of the sub-rectangle of the source image to draw into the destination context
 * @param sHeight the height of the sub-rectangle of the source image to draw into the destination context
 * @param dx the X coordinate in the destination canvas at which to place the top-left corner of the source image
 * @param dy the Y coordinate in the destination canvas at which to place the top-left corner of the source image
 * @param dWidth the width to draw the image in the destination canvas. This allows scaling of the drawn image
 * @param dHeight the height to draw the image in the destination canvas. This allows scaling of the drawn image
 */
@JsxFunction
@SuppressWarnings("unused")
public void drawImage(final Object image, final int sx, final int sy, final Object sWidth, final Object sHeight,
        final Object dx, final Object dy, final Object dWidth, final Object dHeight) {
    final Integer dxI;
    final Integer dyI;
    Integer dWidthI = null;
    Integer dHeightI = null;
    Integer sWidthI = null;
    Integer sHeightI = null;
    if (!Undefined.isUndefined(dx)) {
        dxI = ((Number) dx).intValue();
        dyI = ((Number) dy).intValue();
        dWidthI = ((Number) dWidth).intValue();
        dHeightI = ((Number) dHeight).intValue();
    }
    else {
        dxI = sx;
        dyI = sy;
    }
    if (!Undefined.isUndefined(sWidth)) {
        sWidthI = ((Number) sWidth).intValue();
        sHeightI = ((Number) sHeight).intValue();
    }

    try {
        if (image instanceof HTMLImageElement) {
            final ImageReader imageReader =
                    ((HtmlImage) ((HTMLImageElement) image).getDomNodeOrDie()).getImageReader();
            getRenderingBackend().drawImage(imageReader, dxI, dyI);
        }
    }
    catch (final IOException ioe) {
    }
}
 
Example #15
Source File: HTMLImageElement.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the value of the {@code naturalHeight} property.
 * @return the value of the {@code naturalHeight} property
 */
@JsxGetter
public int getNaturalHeight() {
    final HtmlImage img = (HtmlImage) getDomNodeOrDie();
    try {
        return img.getHeight();
    }
    catch (final IOException e) {
        return 0;
    }
}
 
Example #16
Source File: HTMLImageElement.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the value of the {@code naturalWidth} property.
 * @return the value of the {@code naturalWidth} property
 */
@JsxGetter
public int getNaturalWidth() {
    final HtmlImage img = (HtmlImage) getDomNodeOrDie();
    try {
        return img.getWidth();
    }
    catch (final IOException e) {
        return 0;
    }
}
 
Example #17
Source File: HTMLImageElement.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the {@code onload} event handler for this element.
 * @param onload the {@code onload} event handler for this element
 */
@Override
public void setOnload(final Object onload) {
    super.setOnload(onload);

    // maybe the onload handler was not called so far
    final HtmlImage img = (HtmlImage) getDomNodeOrDie();
    img.doOnLoad();
}
 
Example #18
Source File: CanvasRenderingContext2D.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Draws images onto the canvas.
 *
 * @param image an element to draw into the context
 * @param sx the X coordinate of the top left corner of the sub-rectangle of the source image
 *        to draw into the destination context
 * @param sy the Y coordinate of the top left corner of the sub-rectangle of the source image
 *        to draw into the destination context
 * @param sWidth the width of the sub-rectangle of the source image to draw into the destination context
 * @param sHeight the height of the sub-rectangle of the source image to draw into the destination context
 * @param dx the X coordinate in the destination canvas at which to place the top-left corner of the source image
 * @param dy the Y coordinate in the destination canvas at which to place the top-left corner of the source image
 * @param dWidth the width to draw the image in the destination canvas. This allows scaling of the drawn image
 * @param dHeight the height to draw the image in the destination canvas. This allows scaling of the drawn image
 */
@JsxFunction
@SuppressWarnings("unused")
public void drawImage(final Object image, final int sx, final int sy, final Object sWidth, final Object sHeight,
        final Object dx, final Object dy, final Object dWidth, final Object dHeight) {
    final Integer dxI;
    final Integer dyI;
    Integer dWidthI = null;
    Integer dHeightI = null;
    Integer sWidthI = null;
    Integer sHeightI = null;
    if (dx != Undefined.instance) {
        dxI = ((Number) dx).intValue();
        dyI = ((Number) dy).intValue();
        dWidthI = ((Number) dWidth).intValue();
        dHeightI = ((Number) dHeight).intValue();
    }
    else {
        dxI = sx;
        dyI = sy;
    }
    if (sWidth != Undefined.instance) {
        sWidthI = ((Number) sWidth).intValue();
        sHeightI = ((Number) sHeight).intValue();
    }

    try {
        if (image instanceof HTMLImageElement) {
            final ImageReader imageReader =
                    ((HtmlImage) ((HTMLImageElement) image).getDomNodeOrDie()).getImageReader();
            getRenderingBackend().drawImage(imageReader, dxI, dyI);
        }
    }
    catch (final IOException ioe) {
        if (getBrowserVersion().hasFeature(JS_CANVAS_DRAW_THROWS_FOR_MISSING_IMG)) {
            throw Context.throwAsScriptRuntimeEx(ioe);
        }
    }
}
 
Example #19
Source File: HTMLImageElement.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * JavaScript constructor.
 */
@JsxConstructor({CHROME, FF, FF68, FF60})
public void jsConstructor() {
    final SgmlPage page = (SgmlPage) getWindow().getWebWindow().getEnclosedPage();
    final DomElement fake =
            page.getWebClient().getPageCreator().getHtmlParser()
                .getFactory(HtmlImage.TAG_NAME)
                .createElement(page, HtmlImage.TAG_NAME, null);
    setDomNode(fake);
}
 
Example #20
Source File: HTMLImageElement.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the {@code onload} event handler for this element.
 * @param onload the {@code onload} event handler for this element
 */
@Override
public void setOnload(final Object onload) {
    super.setOnload(onload);

    // maybe the onload handler was not called so far
    final HtmlImage img = (HtmlImage) getDomNodeOrDie();
    img.doOnLoad();
}
 
Example #21
Source File: HTMLImageElement.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the value of the {@code naturalHeight} property.
 * @return the value of the {@code naturalHeight} property
 */
@JsxGetter
public int getNaturalHeight() {
    final HtmlImage img = (HtmlImage) getDomNodeOrDie();
    try {
        return img.getHeight();
    }
    catch (final IOException e) {
        return 0;
    }
}
 
Example #22
Source File: HTMLImageElement.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the value of the {@code naturalWidth} property.
 * @return the value of the {@code naturalWidth} property
 */
@JsxGetter
public int getNaturalWidth() {
    final HtmlImage img = (HtmlImage) getDomNodeOrDie();
    try {
        return img.getWidth();
    }
    catch (final IOException e) {
        return 0;
    }
}
 
Example #23
Source File: Document.java    From HtmlUnit-Android with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new element with the given tag name.
 *
 * @param tagName the tag name
 * @return the new HTML element, or NOT_FOUND if the tag is not supported
 */
@JsxFunction
public Object createElement(String tagName) {
    Object result = NOT_FOUND;
    try {
        final BrowserVersion browserVersion = getBrowserVersion();

        if (browserVersion.hasFeature(JS_DOCUMENT_CREATE_ELEMENT_STRICT)
              && (tagName.contains("<") || tagName.contains(">"))) {
            LOG.info("createElement: Provided string '"
                        + tagName + "' contains an invalid character; '<' and '>' are not allowed");
            throw Context.reportRuntimeError("String contains an invalid character");
        }
        else if (tagName.startsWith("<") && tagName.endsWith(">")) {
            tagName = tagName.substring(1, tagName.length() - 1);

            final Matcher matcher = TAG_NAME_PATTERN.matcher(tagName);
            if (!matcher.matches()) {
                LOG.info("createElement: Provided string '" + tagName + "' contains an invalid character");
                throw Context.reportRuntimeError("String contains an invalid character");
            }
        }

        final SgmlPage page = getPage();
        org.w3c.dom.Node element = page.createElement(tagName);

        if (element instanceof BaseFrameElement) {
            ((BaseFrameElement) element).markAsCreatedByJavascript();
        }
        else if (element instanceof HtmlInput) {
            ((HtmlInput) element).markAsCreatedByJavascript();
        }
        else if (element instanceof HtmlImage) {
            ((HtmlImage) element).markAsCreatedByJavascript();
        }
        else if (element instanceof HtmlRp) {
            ((HtmlRp) element).markAsCreatedByJavascript();
        }
        else if (element instanceof HtmlRt) {
            ((HtmlRt) element).markAsCreatedByJavascript();
        }
        else if (element instanceof HtmlScript) {
            ((HtmlScript) element).markAsCreatedByJavascript();
        }
        else if (element instanceof HtmlUnknownElement) {
            ((HtmlUnknownElement) element).markAsCreatedByJavascript();
        }
        else if (element instanceof HtmlSvg) {
            element = UnknownElementFactory.instance.createElementNS(page, "", "svg", null);
            ((HtmlUnknownElement) element).markAsCreatedByJavascript();
        }
        final Object jsElement = getScriptableFor(element);

        if (jsElement == NOT_FOUND) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("createElement(" + tagName
                    + ") cannot return a result as there isn't a JavaScript object for the element "
                    + element.getClass().getName());
            }
        }
        else {
            result = jsElement;
        }
    }
    catch (final ElementNotFoundException e) {
        // Just fall through - result is already set to NOT_FOUND
    }
    return result;
}
 
Example #24
Source File: HTMLImageElement.java    From htmlunit with Apache License 2.0 4 votes vote down vote up
/**
 * Support for the image.complete property.
 * @return the value of the {@code complete} property
 */
@JsxGetter
public boolean isComplete() {
    return ((HtmlImage) getDomNodeOrDie()).isComplete();
}
 
Example #25
Source File: Document.java    From htmlunit with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new element with the given tag name.
 *
 * @param tagName the tag name
 * @return the new HTML element, or NOT_FOUND if the tag is not supported
 */
@JsxFunction
public Object createElement(String tagName) {
    Object result = NOT_FOUND;
    try {
        if (tagName.contains("<") || tagName.contains(">")) {
            if (LOG.isInfoEnabled()) {
                LOG.info("createElement: Provided string '"
                            + tagName + "' contains an invalid character; '<' and '>' are not allowed");
            }
            throw Context.reportRuntimeError("String contains an invalid character");
        }
        else if (tagName.length() > 0 && tagName.charAt(0) == '<' && tagName.endsWith(">")) {
            tagName = tagName.substring(1, tagName.length() - 1);

            final Matcher matcher = TAG_NAME_PATTERN.matcher(tagName);
            if (!matcher.matches()) {
                if (LOG.isInfoEnabled()) {
                    LOG.info("createElement: Provided string '" + tagName + "' contains an invalid character");
                }
                throw Context.reportRuntimeError("String contains an invalid character");
            }
        }

        final SgmlPage page = getPage();
        org.w3c.dom.Node element = page.createElement(tagName);

        if (element instanceof BaseFrameElement) {
            ((BaseFrameElement) element).markAsCreatedByJavascript();
        }
        else if (element instanceof HtmlInput) {
            ((HtmlInput) element).markAsCreatedByJavascript();
        }
        else if (element instanceof HtmlImage) {
            ((HtmlImage) element).markAsCreatedByJavascript();
        }
        else if (element instanceof HtmlRp) {
            ((HtmlRp) element).markAsCreatedByJavascript();
        }
        else if (element instanceof HtmlRt) {
            ((HtmlRt) element).markAsCreatedByJavascript();
        }
        else if (element instanceof HtmlScript) {
            ((HtmlScript) element).markAsCreatedByJavascript();
        }
        else if (element instanceof HtmlUnknownElement) {
            ((HtmlUnknownElement) element).markAsCreatedByJavascript();
        }
        else if (element instanceof HtmlSvg) {
            element = UnknownElementFactory.instance.createElementNS(page, "", "svg", null);
            ((HtmlUnknownElement) element).markAsCreatedByJavascript();
        }
        final Object jsElement = getScriptableFor(element);

        if (jsElement == NOT_FOUND) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("createElement(" + tagName
                    + ") cannot return a result as there isn't a JavaScript object for the element "
                    + element.getClass().getName());
            }
        }
        else {
            result = jsElement;
        }
    }
    catch (final ElementNotFoundException e) {
        // Just fall through - result is already set to NOT_FOUND
    }
    return result;
}
 
Example #26
Source File: HTMLImageElement.java    From HtmlUnit-Android with Apache License 2.0 4 votes vote down vote up
/**
 * Support for the image.complete property.
 * @return the value of the {@code complete} property
 */
@JsxGetter
public boolean isComplete() {
    return ((HtmlImage) getDomNodeOrDie()).isComplete();
}
 
Example #27
Source File: SimpleScriptable.java    From HtmlUnit-Android with Apache License 2.0 4 votes vote down vote up
/**
 * Builds a new the JavaScript object that corresponds to the specified object.
 * @param domNode the DOM node for which a JS object should be created
 * @return the JavaScript object
 */
@SuppressWarnings("unchecked")
public SimpleScriptable makeScriptableFor(final DomNode domNode) {
    // Get the JS class name for the specified DOM node.
    // Walk up the inheritance chain if necessary.
    Class<? extends SimpleScriptable> javaScriptClass = null;
    if (domNode instanceof HtmlImage && "image".equals(((HtmlImage) domNode).getOriginalQualifiedName())
            && ((HtmlImage) domNode).wasCreatedByJavascript()) {
        if (domNode.hasFeature(HTMLIMAGE_HTMLELEMENT)) {
            javaScriptClass = HTMLElement.class;
        }
        else if (domNode.hasFeature(HTMLIMAGE_HTMLUNKNOWNELEMENT)) {
            javaScriptClass = HTMLUnknownElement.class;
        }
    }
    if (javaScriptClass == null) {
        final JavaScriptEngine javaScriptEngine =
                (JavaScriptEngine) getWindow().getWebWindow().getWebClient().getJavaScriptEngine();
        for (Class<?> c = domNode.getClass(); javaScriptClass == null && c != null; c = c.getSuperclass()) {
            javaScriptClass = (Class<? extends SimpleScriptable>) javaScriptEngine.getJavaScriptClass(c);
        }
    }

    final SimpleScriptable scriptable;
    if (javaScriptClass == null) {
        // We don't have a specific subclass for this element so create something generic.
        scriptable = new HTMLElement();
        if (LOG.isDebugEnabled()) {
            LOG.debug("No JavaScript class found for element <" + domNode.getNodeName() + ">. Using HTMLElement");
        }
    }
    else {
        try {
            scriptable = javaScriptClass.newInstance();
        }
        catch (final Exception e) {
            throw Context.throwAsScriptRuntimeEx(e);
        }
    }
    initParentScope(domNode, scriptable);

    scriptable.setPrototype(getPrototype(javaScriptClass));
    scriptable.setDomNode(domNode);

    return scriptable;
}
 
Example #28
Source File: SimpleScriptable.java    From htmlunit with Apache License 2.0 4 votes vote down vote up
/**
 * Builds a new the JavaScript object that corresponds to the specified object.
 * @param domNode the DOM node for which a JS object should be created
 * @return the JavaScript object
 */
@SuppressWarnings("unchecked")
public SimpleScriptable makeScriptableFor(final DomNode domNode) {
    // Get the JS class name for the specified DOM node.
    // Walk up the inheritance chain if necessary.
    Class<? extends SimpleScriptable> javaScriptClass = null;
    if (domNode instanceof HtmlImage && "image".equals(((HtmlImage) domNode).getOriginalQualifiedName())
            && ((HtmlImage) domNode).wasCreatedByJavascript()) {
        if (domNode.hasFeature(HTMLIMAGE_HTMLELEMENT)) {
            javaScriptClass = HTMLElement.class;
        }
        else if (domNode.hasFeature(HTMLIMAGE_HTMLUNKNOWNELEMENT)) {
            javaScriptClass = HTMLUnknownElement.class;
        }
    }
    if (javaScriptClass == null) {
        final JavaScriptEngine javaScriptEngine =
                (JavaScriptEngine) getWindow().getWebWindow().getWebClient().getJavaScriptEngine();
        for (Class<?> c = domNode.getClass(); javaScriptClass == null && c != null; c = c.getSuperclass()) {
            javaScriptClass = (Class<? extends SimpleScriptable>) javaScriptEngine.getJavaScriptClass(c);
        }
    }

    final SimpleScriptable scriptable;
    if (javaScriptClass == null) {
        // We don't have a specific subclass for this element so create something generic.
        scriptable = new HTMLElement();
        if (LOG.isDebugEnabled()) {
            LOG.debug("No JavaScript class found for element <" + domNode.getNodeName() + ">. Using HTMLElement");
        }
    }
    else {
        try {
            scriptable = javaScriptClass.newInstance();
        }
        catch (final Exception e) {
            throw Context.throwAsScriptRuntimeEx(e);
        }
    }
    initParentScope(domNode, scriptable);

    scriptable.setPrototype(getPrototype(javaScriptClass));
    scriptable.setDomNode(domNode);

    return scriptable;
}