Home » Java » How to cast java classes in nashorn?

How to cast java classes in nashorn?

Posted by: admin October 26, 2017 Leave a comment

Questions:

In my application I use javafx and I have a WebView that shows news from website. When any link is clicked inside of this WebView – it should open it in browser, not in WebView. I found code that should work in java:

NodeList nodeList = document.getElementsByTagName("a");
        for (int i = 0; i < nodeList.getLength(); i++)
        {
            Node node= nodeList.item(i);
            EventTarget eventTarget = (EventTarget) node;
            eventTarget.addEventListener("click", new EventListener()
            {
                @Override
                public void handleEvent(Event evt)
                {
                    EventTarget target = evt.getCurrentTarget();
                    HTMLAnchorElement anchorElement = (HTMLAnchorElement) target;
                    String href = anchorElement.getHref();
                    //handle opening URL outside JavaFX WebView
                    System.out.println(href);
                    evt.preventDefault();
                }
            }, false);
        }

But the trick is, that i need to translate it to js(using nashron engine). Here what i have for the moment:

pane.lookup("#newsPane").getEngine().getLoadWorker().stateProperty()["addListener(javafx.beans.value.ChangeListener)"](
    function(o, ov, nv){
        if (nv == javafx.concurrent.Worker.State.SUCCEEDED) {
            // Here the things get started
            var nodes = pane.lookup("#newsPane").getEngine().getDocument().getElementsByTagName("a");
            for(var i=0;i<nodes.getLength();i++){
                var node = nodes.item(i);
                // I got node, but now i need to cast it to EventTarget, but i didn't find anywhere how to do that
                LogHelper.info(node);
                // instead of *node* there should be *eventTarget*, also i'm not sure the code above will work even with EventTarget
                node['addEventListener("click", javafx.event.EventListener)'](
                    function(evt){
                        var target = evt.getCurrentTarget();
                        var href = target.getHref();
                        LogHelper.info(href);
                        evt.preventDefault();
                    }
                )
            }
        }
    });

I found some Java.to() and Java.type(), but I didn’t find out how to cast using them(not sure if it is possible at all). Could anyone give me some advise, please?

Answers: