Html/Javascript debugging in JavaFX WebView

后端 未结 4 1496
无人共我
无人共我 2020-11-28 04:53

Are there any ways to debug javascript and html that is executed within a Javafx WebView? Something similar to Firebug or Chrome\'s developer console?

I have an app

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-28 05:37

    Maybe a bit late to answer, but I think this way is quite simple.

    add javascript listener in java

    Java :

    webengine.getLoadWorker().stateProperty().addListener(new ChangeListener() {
                @Override
                public void changed(ObservableValue observable,
                        State oldValue, State newValue) { 
                         JSObject jsobj = (JSObject) webengine.executeScript("window");                      
                         jsobj.setMember("java", new JSListener());  
                }
            });
    

    Then create the JS listener class in java.

    JSListener java:

    public class JSListener { 
    
            public void log(String text){
        System.out.println(text);
    } 
    }
    

    add javascript in html file

    Javascript:

    var javaReady = function(callback){
        if(typeof callback =='function'){
            if(typeof java !='undefined'){
                callback();
            } else {
                var javaTimeout = 0;
                var readycall = setInterval(function(){
                javaTimeout++; 
                    if(typeof java !='undefined' || javaTimeout > 1000){
                        try{
                            callback();
                        } catch(s){};
                        clearInterval(readycall);
                    }
                },1);
            }
        }
    };
    
                var errorlistener = function(msg, url, line){ 
                javaReady(function(){
                java.log(msg +", url: "+url+ ", line:" + line); 
                }); 
            };
    
          //overide onerror 
            var onerror = errorlistener;
    

    If you want to load html from the outside, you can not to change it, you can use code like this.

    var testsss =  window.open("http://testError.com");  
    testsss.onerror = errorlistener;  
    

    but first you need to add setCreatePopupHandler in java, to make it you can see here: webview not opening the popup window in javafx

提交回复
热议问题