DaveTheMinion
DaveTheMinion

Reputation: 664

Open Hyperlinks in JavaFX WebView with Default Browser

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?

Upvotes: 7

Views: 1800

Answers (1)

sanjay
sanjay

Reputation: 56

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();
                            }
                   }
          }
});

Upvotes: 3

Related Questions