Example usage for org.w3c.dom.events Event getCurrentTarget

List of usage examples for org.w3c.dom.events Event getCurrentTarget

Introduction

In this page you can find the example usage for org.w3c.dom.events Event getCurrentTarget.

Prototype

public EventTarget getCurrentTarget();

Source Link

Document

Used to indicate the EventTarget whose EventListeners are currently being processed.

Usage

From source file:de.betterform.xml.xforms.action.AbstractAction.java

/**
 * This method is called whenever an event occurs of the type for which the
 * <code>EventListener</code> interface was registered.
 *
 * @param event The <code>Event</code> contains contextual information about
 *              the event. It also contains the <code>stopPropagation</code> and
 *              <code>preventDefault</code> methods which are used in determining the
 *              event's flow and default action.
 */// w  ww. j a v  a2  s  .  co  m
public final void handleEvent(Event event) {
    try {
        if (event.getType().equals(this.eventType)) {
            boolean doPerform = false;

            if (this.propagate.equals("stop")) {
                event.stopPropagation();
            }
            if (this.defaultAction.equals("cancel")) {
                event.preventDefault();
            }

            if (getLogger().isTraceEnabled()) {
                String currentEventId = (((Element) event.getCurrentTarget()).getAttribute("id"));
                String targetEventId = (((Element) event.getTarget()).getAttribute("id"));
                LOGGER.trace(
                        "currentEventTargetId: '" + currentEventId + "' eventTargetId:'" + targetEventId + "'");

                getLogger().trace("handling event '" + this.eventType + "' target: "
                        + DOMUtil.getCanonicalPath(this.element) + "' Event Phase: (" + event.getEventPhase()
                        + ")");
            }

            if (getLogger().isDebugEnabled()) {
                switch (event.getEventPhase()) {
                case Event.CAPTURING_PHASE:
                    if (getLogger().isDebugEnabled()) {
                        getLogger().debug("CAPTURING PHASE");
                    }

                    break;
                case Event.AT_TARGET:
                    if (getLogger().isDebugEnabled()) {
                        getLogger().debug("AT_TARGET");
                    }

                    break;
                case Event.BUBBLING_PHASE:
                    if (getLogger().isDebugEnabled()) {
                        getLogger().debug("BUBBLING");
                    }
                    break;
                }
            }

            if (event.getEventPhase() == Event.CAPTURING_PHASE && this.phase.equals("capture")) {
                doPerform = true;
            } else if (event.getEventPhase() == Event.AT_TARGET) {
                doPerform = true;
            } else if (event.getEventPhase() == Event.BUBBLING_PHASE) {
                doPerform = true;
            }

            String targetEventId = (((Element) event.getTarget()).getAttribute("id"));
            if (!(this.eventTargetId.equals(""))) {
                if (event.getType().equals(this.eventType) && targetEventId.equals(this.eventTargetId)) {
                    doPerform = true;
                } else {
                    doPerform = false;
                }
            }

            if (doPerform) {
                performConditional(this.element);
            }
        }
    } catch (Exception e) {
        // handle exception, prevent default action and stop event propagation
        this.container.handleEventException(e);
        event.preventDefault();
        event.stopPropagation();
    }
}

From source file:ai.ilikeplaces.logic.Listeners.widgets.DownTownHeatMap.java

/**
 * Use ItsNatHTMLDocument variable stored in the AbstractListener class
 * Do not call this method anywhere, just implement it, as it will be
 * automatically called by the constructor
 *
 * @param itsNatHTMLDocument_//ww  w.j a va2  s  . c o  m
 * @param hTMLDocument_
 */
@Override
protected void registerEventListeners(final ItsNatHTMLDocument itsNatHTMLDocument_,
        final HTMLDocument hTMLDocument_) {
    UCSignup: {
        itsNatHTMLDocument_.addEventListener((EventTarget) $$(DownTownHeatMapIds.DownTownHeatMapSignupEmail),
                EventType.BLUR.toString(), new EventListener() {
                    final Validator v = new Validator();

                    final Email myemail = email;

                    @Override
                    public void handleEvent(final Event evt_) {
                        myemail.setObj(
                                ((Element) evt_.getCurrentTarget()).getAttribute(MarkupTag.INPUT.value()));
                        if (myemail.validate(v) == 0) {
                            $$(DownTownHeatMapIds.DownTownHeatMapSignupNotifications)
                                    .setTextContent("Email Valid!");
                        } else {
                            $$(DownTownHeatMapIds.DownTownHeatMapSignupNotifications)
                                    .setTextContent("Email INVALID!");
                        }
                    }
                }, false, new NodePropertyTransport(MarkupTag.TEXTAREA.value()));
        itsNatHTMLDocument_.addEventListener((EventTarget) $$(DownTownHeatMapIds.DownTownHeatMapSignupPassword),
                EventType.BLUR.toString(), new EventListener() {
                    final Validator v = new Validator();

                    final Password mypassword = password;

                    @Override
                    public void handleEvent(final Event evt_) {
                        mypassword.setObj(
                                ((Element) evt_.getCurrentTarget()).getAttribute(MarkupTag.INPUT.value()));
                        if (mypassword.validate(v) == 0) {
                            $$(DownTownHeatMapIds.DownTownHeatMapSignupNotifications)
                                    .setTextContent("Password Valid!");
                        } else {
                            $$(DownTownHeatMapIds.DownTownHeatMapSignupNotifications)
                                    .setTextContent("Password INVALID!");
                        }
                    }
                }, false, new NodePropertyTransport(MarkupTag.TEXTAREA.value()));

        itsNatHTMLDocument_.addEventListener((EventTarget) $$(DownTownHeatMapIds.DownTownHeatMapSignupButton),
                EventType.CLICK.toString(), new EventListener() {
                    final Validator v = new Validator();

                    final Email myemail = email;

                    final Password mypassword = password;

                    @Override
                    public void handleEvent(final Event evt_) {
                        if (myemail.validate(v) == 0 && mypassword.validate(v) == 0) {
                            if (!DB.getHumanCRUDHumanLocal(true).doDirtyCheckHuman(myemail.getObj())
                                    .returnValue()) {
                                final Return<Boolean> humanCreateReturn = DB.getHumanCRUDHumanLocal(true)
                                        .doCHuman(new HumanId().setObjAsValid(email.getObj()), mypassword,
                                                myemail);

                                if (humanCreateReturn.valid() && humanCreateReturn.returnValue()) {

                                    UserIntroduction.createIntroData(new HumanId(email.getObj()));

                                    final String activationURL = new Parameter(
                                            "http://www.ilikeplaces.com/" + "activate")
                                                    .append(ServletLogin.Username, myemail.getObj(), true)
                                                    .append(ServletLogin.Password,
                                                            DB.getHumanCRUDHumanLocal(true)
                                                                    .doDirtyRHumansAuthentication(
                                                                            new HumanId(myemail.getObj()))
                                                                    .returnValue().getHumanAuthenticationHash())
                                                    .get();

                                    String htmlBody = Bate.getHTMLStringForOfflineFriendInvite("I Like Places",
                                            email.getObj());

                                    htmlBody = htmlBody.replace(URL, activationURL);
                                    htmlBody = htmlBody.replace(Bate.PASSWORD_ADVICE, "");
                                    htmlBody = htmlBody.replace(Bate.PASSWORD_DETAILS, "");

                                    SendMail.getSendMailLocal().sendAsHTMLAsynchronously(myemail.getObj(),
                                            "I Like Places prides you with an Exclusive Invite!", htmlBody);

                                    $$sendJSStmt(JSCodeToSend
                                            .redirectPageWithURL(Controller.Page.Activate.getURL()));
                                } else {
                                    $$(DownTownHeatMapIds.DownTownHeatMapSignupNotifications)
                                            .setTextContent("Email INVALID!");
                                }

                                /*final Return<Boolean> humanCreateReturn = DB.getHumanCRUDHumanLocal(true).doCHuman(
                                    new HumanId().setObjAsValid(email.getObj()),
                                    mypassword,
                                    myemail);
                                        
                                if (humanCreateReturn.returnValue()) {
                                final String activationURL = new Parameter("http://www.ilikeplaces.com/" + "activate")
                                        .append(ServletLogin.Username, myemail.getObj(), true)
                                        .append(ServletLogin.Password,
                                                DB.getHumanCRUDHumanLocal(true).doDirtyRHumansAuthentication(new HumanId(myemail.getObj()))
                                                        .returnValue()
                                                        .getHumanAuthenticationHash())
                                        .get();
                                        
                                final String mail = MessageFormat.format(RBGet.gui().getString("SIGNUP_BODY"), RBGet.globalConfig.getString("noti_mail"))
                                        .replace("activationURL", "<a href='" +
                                                activationURL + "' >" + activationURL + "</a>");
                                SendMail.getSendMailLocal().sendAsHTMLAsynchronously(
                                        myemail.getObj(),
                                        RBGet.gui().getString("SIGNUP_HEADER"),
                                        mail);
                                $$sendJSStmt(JSCodeToSend.redirectPageWithURL(Controller.Page.Activate.getURL()));
                                }*/
                            } else {
                                $$(DownTownHeatMapIds.DownTownHeatMapSignupNotifications)
                                        .setTextContent("This email is TAKEN!:(");
                            }
                        } else {
                            //Ignored as the individual validators would've reported the error by now
                        }
                    }
                }, false, new NodePropertyTransport(MarkupTag.TEXTAREA.value()));
    }

    itsNatHTMLDocument_.addEventListener((EventTarget) $$(DownTownHeatMapIds.DownTownHeatMapWOEID),
            EventType.BLUR.toString(), new EventListener() {
                final Validator v = new Validator();

                RefObj<String> woeid;

                @Override
                public void handleEvent(final Event evt_) {
                    woeid = new Info(
                            ((Element) evt_.getCurrentTarget()).getAttribute(MarkupTag.TEXTAREA.value()));

                    if (woeid.validate(v) == 0) {
                        elementToUpdateWithWOEID.setAttribute(MarkupTag.INPUT.value(),
                                woeid.getObjectAsValid());
                    } else {
                    }
                }
            }, false, new NodePropertyTransport(MarkupTag.TEXTAREA.value()));

    itsNatHTMLDocument_.addEventListener((EventTarget) $$(DownTownHeatMapIds.DownTownHeatMapBB),
            EventType.BLUR.toString(), new EventListener() {
                final Validator v = new Validator();

                final GeoCoord geoCoordSW = new GeoCoord();

                final GeoCoord geoCoordNE = new GeoCoord();

                final ItsNatDocument ind = itsNatDocument_;

                final HumanId myhumanId = humanId;

                @Override
                public void handleEvent(final Event evt_) {
                    final GeoCoord[] geoCoord = GeoCoord.getGeoCoordsByBounds(
                            ((Element) evt_.getCurrentTarget()).getAttribute(MarkupTag.TEXTAREA.value()));

                    if (geoCoord[0].validate(v) == 0 && geoCoord[1].validate(v) == 0) {
                        elementToUpdateWithWOEID.setAttribute(MarkupTag.INPUT.value(),
                                geoCoord[0].toString() + COMMA + geoCoord[1]);

                        /////////////////////////////
                        final Double latitudeLB = geoCoord[0].getObjectAsValid().getLatitude();
                        final Double latitudeTR = geoCoord[1].getObjectAsValid().getLatitude();
                        final Double longitudeLB = geoCoord[0].getObjectAsValid().getLongitude();
                        final Double longitudeTR = geoCoord[1].getObjectAsValid().getLongitude();

                        final Set<Rawspot> rs = new HashSet<Rawspot>() {
                            //Initializing HashSet as an anonymous class. God speed!
                            /*StaticBlockInsideSetToAddElementsEasily*/ {
                                UCILikePlacesPlaces: {
                                    Return<List<PrivateEvent>> RETURN = DB.getHumanCrudPrivateEventLocal(true)
                                            .doRPrivateEventsByBoundsAsSystem(latitudeLB, latitudeTR,
                                                    longitudeLB, longitudeTR);

                                    if (RETURN.valid()) {
                                        final List<PrivateEvent> privateEvents__ = RETURN.returnValue();
                                        for (final PrivateEvent privateEvent : privateEvents__) {
                                            add(new Rawspot(
                                                    new W3CPoint(
                                                            privateEvent.getPrivateLocation()
                                                                    .getPrivateLocationLatitude(),
                                                            privateEvent.getPrivateLocation()
                                                                    .getPrivateLocationLongitude()),
                                                    privateEvent.getPrivateLocation()
                                                            .getPrivateLocationName()));
                                        }
                                    }
                                }

                                UCGooglePlaces: {
                                    try {
                                        final double latitudeAverage = (latitudeLB + latitudeTR) / 2;
                                        final double longitudeAverage = (longitudeLB + longitudeTR) / 2;

                                        final JSONObject placesJsonObject = getGooglePlaces(latitudeAverage,
                                                longitudeAverage, (long) (Math.abs(latitudeAverage - latitudeLB)
                                                        * APPROX_LENGTH_OF_ONE_LAT),
                                                COMMON_PLACE_TYPES);

                                        final JSONArray placesJsonArray = placesJsonObject
                                                .getJSONArray(RESULTS);

                                        for (int i = 0; i < placesJsonArray.length(); i++) {
                                            final JSONObject lngLat = placesJsonArray.getJSONObject(i)
                                                    .getJSONObject(GEOMETRY)
                                                    .getJSONObject(LOCATION_JSON_OBJ_KEY);
                                            add(new Rawspot(
                                                    new W3CPoint(Double.parseDouble(lngLat.getString(LAT)),
                                                            Double.parseDouble(lngLat.getString(LNG))),
                                                    placesJsonArray.getJSONObject(i).getString(NAME)
                                                            .toLowerCase()));
                                            add(new Rawspot(
                                                    new W3CPoint(Double.parseDouble(lngLat.getString(LAT)),
                                                            Double.parseDouble(lngLat.getString(LNG))),
                                                    placesJsonArray.getJSONObject(i).getString(NAME)
                                                            .toLowerCase()));
                                        }
                                    } catch (final Exception e) {
                                        Loggers.ERROR.error(FAILED_TO_FETCH_GOOGLE_PLACES_DATA, e);
                                    }
                                }

                                UCYahooUpcomingEvents: {

                                    try {
                                        final double latitudeAverage = (latitudeLB + latitudeTR) / 2;
                                        final double longitudeAverage = (longitudeLB + longitudeTR) / 2;

                                        final JSONObject jsonObject = Modules.getModules()
                                                .getYahooUplcomingFactory()
                                                .getInstance("http://upcoming.yahooapis.com/services/rest/")
                                                .get("", new HashMap<String, String>() {
                                                    {//Don't worry, this is a static initializer of this map :)
                                                        put("method", "event.search");
                                                        put("location",
                                                                "" + latitudeAverage + "," + longitudeAverage);
                                                        put("format", "json");
                                                    }
                                                }

            );
                                        final JSONArray events = jsonObject.getJSONObject("rsp")
                                                .getJSONArray("event");
                                        for (int i = 0; i < events.length(); i++) {
                                            final JSONObject eventJSONObject = new JSONObject(
                                                    events.get(i).toString());
                                            add(new Rawspot(new W3CPoint(
                                                    Double.parseDouble(eventJSONObject.getString(LATITUDE)),
                                                    Double.parseDouble(eventJSONObject.getString(LONGITUDE))),
                                                    eventJSONObject.getString(NAME).toLowerCase()));
                                            add(new Rawspot(new W3CPoint(
                                                    Double.parseDouble(eventJSONObject.getString(LATITUDE)),
                                                    Double.parseDouble(eventJSONObject.getString(LONGITUDE))),
                                                    eventJSONObject.getString(NAME).toLowerCase()));

                                        }
                                    } catch (final Exception e) {
                                        Loggers.error(ERROR_PROCESSING_YAHOO_UPCOMING_DATA, e);
                                    }
                                }
                            }
                        };

                        final BoundingBox bb = new BoundingBox().setObj(latitudeLB, longitudeLB, latitudeTR,
                                longitudeTR);

                        final HotspotAnalyzer hsa = new HotspotAnalyzer(rs,
                                (BoundingBox) bb.validateThrowAndGetThis());

                        //                    final Map<Integer, Map<Integer, Hotspot>> hotspots = hsa.getHotspots();
                        final Hotspot[][] hotspots = hsa.getHotspots();

                        boolean foundAnySpots = false;

                        for (final Hotspot[] hotspotspitch : hotspots) {
                            for (final Hotspot yaw : hotspotspitch) {
                                final W3CPoint coords = yaw.getCoordinates();

                                if (yaw.getCoordinates() != null) {
                                    foundAnySpots = true;

                                    final Double latitude = coords.getLatitude();
                                    final Double longitude = coords.getLongitude();

                                    final String commonName = yaw.getCommonName().replace("\"", "'");

                                    final long hits = yaw.getHits();

                                    generateMarker(latitude, longitude, commonName, hits);

                                    generateMarkerEvents(coords, commonName, hits);

                                    $$sendJSStmt(PROCESS_MARKER + OPEN_BRACKET + (OPEN_BRACE
                                            + (HTIS + COLON + THIS) + COMMA
                                            + (COMMON_NAME + COLON + QUOTE + commonName + QUOTE) + COMMA
                                            + (LATITUDE + COLON + coords.getLatitude()) + COMMA
                                            + (LONGITUDE + COLON + coords.getLongitude()) + COMMA
                                            + (URL + COLON + QUOTE
                                                    + new Parameter(Controller.Page.Organize.getURL())
                                                            .append(Controller.Page.DocOrganizeCategory, 143,
                                                                    true)
                                                            .append(WOEIDGrabber.WOEHINT,
                                                                    coords.getLatitude() + COMMA
                                                                            + coords.getLongitude())
                                                            .get()
                                                    + QUOTE)
                                            + CLOSE_BRACE) + CLOSE_BRACKET);
                                }
                            }
                        }

                        if (humanId.validate() == 0) {//User is logged in
                            final List<PrivateLocation> usersOwnPrivateLocations = DB
                                    .getHumanCRUDHumanLocal(false).doDirtyRHumansPrivateLocation(humanId)
                                    .returnValue().getPrivateLocationsOwned();

                            List<PrivateLocation> usersOwnPrivateLocationsWithinBounds = new ArrayList<PrivateLocation>();

                            UCFindLocationsWithinBounds: {
                                for (final PrivateLocation privateLocation : usersOwnPrivateLocations) {
                                    final W3CPoint w3CPoint = new W3CPoint(
                                            privateLocation.getPrivateLocationLatitude(),
                                            privateLocation.getPrivateLocationLongitude());
                                    if (bb.bounds(w3CPoint)) {
                                        usersOwnPrivateLocationsWithinBounds.add(privateLocation);
                                    }
                                }
                            }

                            for (final PrivateLocation userOwnPrivateLocation : usersOwnPrivateLocationsWithinBounds) {
                                generateMyMarker(userOwnPrivateLocation.getPrivateLocationLatitude(),
                                        userOwnPrivateLocation.getPrivateLocationLongitude(),
                                        userOwnPrivateLocation.getPrivateLocationName().replaceAll("'", "\\'"),
                                        1);//@TODO Hits needs to be fixed in an efficient way

                                generateMarkerEvents(
                                        new W3CPoint(userOwnPrivateLocation.getPrivateLocationLatitude(),
                                                userOwnPrivateLocation.getPrivateLocationLongitude()),
                                        userOwnPrivateLocation.getPrivateLocationName().replaceAll("'", "\\'"),
                                        (long) 1);//@TODO Hits needs to be fixed in an efficient way

                                $$sendJSStmt(PROCESS_MARKER + OPEN_BRACKET + (OPEN_BRACE + (HTIS + COLON + THIS)
                                        + COMMA
                                        + (COMMON_NAME + COLON + QUOTE
                                                + userOwnPrivateLocation.getPrivateLocationName()
                                                        .replaceAll("'", "\\'")
                                                + QUOTE)
                                        + COMMA
                                        + (LATITUDE
                                                + COLON + userOwnPrivateLocation.getPrivateLocationLatitude())
                                        + COMMA
                                        + (LONGITUDE
                                                + COLON + userOwnPrivateLocation.getPrivateLocationLongitude())
                                        + COMMA
                                        + (URL + COLON + QUOTE
                                                + new Parameter(Controller.Page.Organize.getURL())
                                                        .append(Controller.Page.DocOrganizeCategory, 143, true)
                                                        .append(WOEIDGrabber.WOEHINT,
                                                                userOwnPrivateLocation
                                                                        .getPrivateLocationLatitude()
                                                                        + COMMA
                                                                        + userOwnPrivateLocation
                                                                                .getPrivateLocationLongitude())
                                                        .get()
                                                + QUOTE)
                                        + CLOSE_BRACE) + CLOSE_BRACKET);
                            }
                        }

                        //                    for (int i = 0; i < hotspots.size(); i++) {
                        //                        for (int j = 0; j < hotspots.get(i).size(); j++) {
                        //                            final W3CPoint coords = hotspots.get(i).get(j).getCoordinates();
                        //
                        //                            if (coords != null) {
                        //                                final Double latitudeLB = coords.getLatitude();
                        //                                final Double longitude = coords.getLongitude();
                        //
                        //                                final String commonName = hotspots.get(i).get(j).getCommonName();
                        //
                        //                                final long hits = hotspots.get(i).get(j).getHits();
                        //
                        //                                generateMarker(latitudeLB, longitude, commonName, hits);
                        //
                        //                                generateMarkerEvents(coords,commonName,hits);
                        //
                        //                            }
                        //                        }
                        //                    }

                        if (foundAnySpots) {
                            $$sendJSStmt(NOTIFY_USER_POSITIVE);
                        } else {
                            $$sendJSStmt(NOTIFY_USER_NEGATIVE);
                        }
                    } else {
                    }
                }
            }, false, new NodePropertyTransport(MarkupTag.TEXTAREA.value()));
}

From source file:com.vladsch.idea.multimarkdown.editor.MultiMarkdownFxPreviewEditor.java

protected void workerStateChanged(ObservableValue<? extends Worker.State> observable, Worker.State oldState,
        Worker.State newState) {// w w w  . ja v a2 s  . c o  m
    //logger.info("[" + instance + "] " + "newState: " + newState + ", oldState: " + oldState);
    if (newState == Worker.State.SUCCEEDED) {
        // restore scroll if we had it
        JSObject jsobj = (JSObject) webEngine.executeScript("window");
        jsobj.setMember("java", new JSBridge(this));

        EventListener listener = new EventListener() {
            @Override
            public void handleEvent(org.w3c.dom.events.Event evt) {
                evt.stopPropagation();
                evt.preventDefault();

                if (project.isDisposed())
                    return;

                Element link = (Element) evt.getCurrentTarget();
                org.w3c.dom.Document doc = webEngine.getDocument();
                final String href = link.getAttribute("href");
                if (href.charAt(0) == '#') {
                    if (href.length() != 1) {
                        // tries to go to an anchor
                        String hrefName = href.substring(1);
                        // scroll it into view
                        try {
                            JSObject result = (JSObject) webEngine.executeScript("(function () {\n"
                                    + "    var elemTop = 0;\n" + "    var elems = '';\n"
                                    + "    var elem = window.document.getElementById('" + hrefName + "');\n"
                                    + "    if (!elem) {\n"
                                    + "        var elemList = window.document.getElementsByTagName('a');\n"
                                    + "        for (a in elemList) {\n"
                                    + "            var aElem = elemList[a]\n"
                                    + "            if (aElem.hasOwnProperty('name') && aElem.name == '"
                                    + hrefName + "') {\n" + "                elem = aElem;\n"
                                    + "                break;\n" + "            }\n" + "        }\n" + "    }\n"
                                    + "    if (elem) {\n"
                                    + "        while (elem && elem.tagName !== 'HTML') {\n"
                                    + "            elems += ',' + elem.tagName + ':' + elem.offsetTop\n"
                                    + "            if (elem.offsetTop) {\n"
                                    + "                elemTop += elem.offsetTop;\n"
                                    + "                break;\n" + "            }\n"
                                    + "            elem = elem.parentNode\n" + "        }\n" + "    }\n"
                                    + "    return { elemTop: elemTop, elems: elems, found: !!elem };\n" + "})()"
                                    + "");
                            int elemTop = (Integer) result.getMember("elemTop");
                            boolean elemFound = (Boolean) result.getMember("found");
                            String parentList = (String) result.getMember("elems");
                            //logger.trace(parentList);
                            if (elemFound)
                                webEngine.executeScript("window.scroll(0, " + elemTop + ")");
                        } catch (JSException ex) {
                            String error = ex.toString();
                            logger.info("[" + instance + "] " + "JSException on script", ex);
                        }
                    }
                } else {
                    MultiMarkdownPathResolver.launchExternalLink(project, href);
                }
            }
        };

        NodeList nodeList;
        org.w3c.dom.Document doc = webEngine.getDocument();
        if (doc != null) {
            ((EventTarget) doc.getDocumentElement()).addEventListener("contextmenu", new EventListener() {
                @Override
                public void handleEvent(Event evt) {
                    evt.preventDefault();
                }
            }, false);

            Element el = doc.getElementById("a");
            nodeList = doc.getElementsByTagName("a");
            for (int i = 0; i < nodeList.getLength(); i++) {
                ((EventTarget) nodeList.item(i)).addEventListener("click", listener, false);
            }

            // all images are mapped during conversion. Any relative ones are not resolved.
            //nodeList = doc.getElementsByTagName("img");
            //for (int i = 0; i < nodeList.getLength(); i++) {
            //    HTMLImageElementImpl imgNode = (HTMLImageElementImpl) nodeList.item(i);
            //    String src = imgNode.getSrc();
            //    if (!src.startsWith("http://") && !src.startsWith("https://") && !src.startsWith("ftp://") && !src.startsWith("file://")) {
            //        // relative to document, change it to absolute file://
            //        // this means it does not resolve, leave it
            //        if (!project.isDisposed() && containingFile != null && resolver != null) {
            //            ImageLinkRef linkRef = new ImageLinkRef(new FileRef(containingFile), src, null, null);
            //            PathInfo resolvedTarget = resolver.resolve(linkRef, LinkResolver.ONLY_URI, null);
            //
            //            assert resolvedTarget == null || resolvedTarget instanceof LinkRef && linkRef.isURI() : "Expected URI LinkRef, got " + linkRef;
            //            if (resolvedTarget != null) {
            //                imgNode.setSrc(resolvedTarget.getFilePath());
            //            }
            //        }
            //    }
            //}
        }

        if (pageScript != null && pageScript.length() > 0) {
            webEngine.executeScript(pageScript);
        }

        // enable debug if it is enabled in settings
        if (MultiMarkdownGlobalSettings.getInstance().enableFirebug.getValue()) {
            enableDebug();
        }

        String scroll = scrollOffset;
        if (scroll != null) {
            try {
                //webEngine.executeScript("window.java.log('test info')");
                webEngine.executeScript(
                        "" + "window.setTimeout(function () { " + "    window.java.log('before scroll');"
                                + "    " + scroll + ";\n" + "    window.java.log('after scroll');" + "}, 50);");
            } catch (Exception e) {
                logger.info("[" + instance + "] " + "JSException on script", e);
            }
        }

        try {
            webEngine.executeScript("window.addEventListener('scroll', function() { "
                    + "    window.java.onScroll();" + "    window.setTimeout(function () { "
                    + "        window.java.repaint()" + "    }, 100);" + "})");
        } catch (Exception e) {
            logger.info("[" + instance + "] " + "", e);
        }

        //if (needStyleSheetUpdate) {
        //    setStyleSheet();
        //}
    }

    if (newState == Worker.State.READY || newState == Worker.State.FAILED
            || newState == Worker.State.SUCCEEDED) {
        htmlWorkerRunning = false;
    }
}