Search code examples
javajavafxwebviewkioskjavafx-webengine

How to deny access to webpage from javafx web


I am currently working on a kiosk project in javafx. It uses WebView/WebEngine. I need to allow the kiosk admin to ban access to certain websites, I know how to check if they match, but how do I hook webengine so that it will tell me when it goes to a page. the kiosk checks it, and then I can redirect it to a blockpage url. How can I do this


Solution

  • Add a listener to the locationProperty() of the WebView's WebEngine and, within the listener, check if the new location matches your blacklist.

    For example (in Java 8):

    WebEngine engine = webview.getEngine();
    engine.locationProperty().addListener((observable, oldValue, newValue) -> {
        if (newValue.contains("badsite")) { // replace with your URL checking logic
            Platform.runLater(() -> {
                // Load your block page url
                engine.load("http://example.com"));
            }
        }
    });
    

    As per this answer to a similar question, the JVM may crash if the engine.load() call is not wrapped in a Platform.runLater().