Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open Hyperlinks in JavaFX WebView with Default Browser

Tags:

javafx

webview

I am writing a Java program that uses a Swing-based user interface, however I needed access to WebView, so I implemented a JFXPanel to take care of that. WebView is supposed to load an advertisement banner in to the program that the user can click on if the want. Currently, when the advertisement is clicked, the new page is loading within WebView. If possible, I would like to have the page open in the user's default browser and have the page containing the advertisement refresh. How can I achieve this?

like image 561
DaveTheMinion Avatar asked Aug 09 '15 22:08

DaveTheMinion


1 Answers

engine.getLoadWorker().stateProperty().addListener(new ChangeListener<Worker.State>()
        {
            @Override
            public void changed(ObservableValue<? extends Worker.State> observable, Worker.State oldValue,
                    Worker.State newValue)
            {
            String toBeopen =
                            engine.getLoadWorker().getMessage().trim();
                    System.out.println("tobeopen: " + toBeopen);
                    if (toBeopen.contains("http://") || toBeopen.contains("https://")) {
                        engine.getLoadWorker().cancel();
                        try {
                                Desktop.getDesktop().browse(new URL(toBeopen).toURI());
                            }
                            catch (MalformedURLException e) {
                                e.printStackTrace();
                            }
                            catch (URISyntaxException e) {
                                e.printStackTrace();
                            }
                            catch (IOException e) {
                                e.printStackTrace();
                            }
                   }
          }
});
like image 82
sanjay Avatar answered Sep 19 '22 11:09

sanjay