Search code examples
javajavafxwebviewjavafx-webengine

How to Open Links in a browser of a website Inside a Webviewer JavaFx


I have this VBox holding a WebView container. What I can not figure out is how to make the WebViewer open links in a new tab or window in any browser not Viewing it on the program.

@FXML private VBox WebViewer;

public void initialize(URL location, ResourceBundle resources) {
    WebView browser = new WebView();
    WebEngine webEngine = browser.getEngine();
    webEngine.load("http://google.com/");

    WebViewer.getChildren().addAll(browser);
}

Solution

  • I assume you've figured this out by now, but the way I would have done it involves using the special JavaScript API in the WebEngine to call a java method and open it that way.

    Create a class, like this one:

    public class eagler {
        public void open(String url) {
            java.awt.Desktop.getDesktop().browse(url);
        }
    }
    

    Then, add this before your webengine.load method:

        webEngine.getLoadWorker().stateProperty().addListener(
                new ChangeListener<State>() {
                    @Override
                    public void changed(ObservableValue<? extends State> ov,
                        State oldState, State newState) {   
                        if (newState == State.SUCCEEDED) {
                                JSObject win = (JSObject) webEngine.executeScript("window");
                                win.setMember("eagler", new eagler());
                            }
                        }
                    }
            );
    

    Now, whenever you want to open an external page...

    <button onclick="eagler.open('http://bitly.com/98K8eH')">Click Me</button>