Search code examples
javajavafxwebviewwebengine

webView JavaFX Redirect A Certain URL When Accessed


I am using javaFX webView how can I redirect a certain URL to other.

example :-

if user access 
example.com/pathabc
redirect it to
example.com/pathxyz

Thank You.

Edit :-

Let's say if I loaded example.com (I can't change this I have to load example.com)

The page example.com has a link to example.com/pathabc and when the user clicks on it can be accessed.

But I don't want to user to access example.com/pathabc so I want to redirect it example.com/pathxyz

Please tell me how can I redirect it.


Solution

  • You can add a listener to the locationProperty, and redirect it if the new location matches a URL you want to redirect.

    e.g.

    webEngine.locationProperty().addListener((obs, oldLocation, newLocation) -> {
        if (newLocation != null && newLocation.endsWith("example.com/pathabc")) {
            webEngine.load("http://example.com/pathxyz");
        }
    });
    

    You will probably need to refine the criterion for a matching URL, etc, but this should give you the basic idea.