Inject bridge-code in JavaFX WebView before page-load?

廉价感情. 提交于 2019-12-11 09:35:22

问题


I want to load some content or page in a JavaFX WebView and offer a Bridge object to Java so the content of the page can do calls into java.

The basic concept of how to do this is described here: https://blogs.oracle.com/javafx/entry/communicating_between_javascript_and_javafx

Now my question is: When is a good time inject the bridge-object into the WebView so it is available as soon as possible.

One option would be after page load as described here: https://stackoverflow.com/a/17612361/1520422

But is there a way to inject this sooner (before the page content itself is initialized), so the bridge-object is available DURING page-load (and not only after page-load)?


回答1:


Since no one has answered, I'll tell you how I'm doing it, although it is ugly. This provides the ability for the page to function normally in non-Java environments but receive a Java object in Java environments.

I start by providing an onStatusChanged handler to the WebEngine. It listens for a magic value for window.status. If the magic value is received, the handler installs the Java object. (In my case, it's more complex, because I have some more complex orchestration: I'm executing a script that provides a client-side API for the page and then sets another magic value on window.status to cause the Java object to be sent to an initialization method of the client-side API).

Then in my target page, I have the following code in the first script in the page:

window.status = "MY-MAGIC-VALUE";
window.status = "";

This code is essentially a no-op in a "normal" browser but triggers the initialization when running in the custom JavaFX embedding.




回答2:


In Java 8, you can trigger event changing from SCHEDULED to RUNNING to inject objects at this time. The objects will present in WebEngine before JavaScript running. Java 7, I see the state machine quite differs in operating, no solution given for Java 7.

webEngine.getLoadWorker().stateProperty().addListener(
   new ChangeListener<State>(){
   public void changed(ObservableValue<? extends State> ov, 
             State oldState, 
             State newState) 
         {
            // System.out.println("old: "+oldState+", new: "+newState);
             if(newState == State.RUNNING && 
                oldState == State.SCHEDULED){
                 JSObject window = (JSObject)webEngine.executeScript("window");
                 window.setMember("foutput", foutput);
             }
         }
});


来源:https://stackoverflow.com/questions/26400925/inject-bridge-code-in-javafx-webview-before-page-load

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!