Wednesday, March 28, 2012

JavaFX 2.0: OnAlert EventHandler of WebEngine.

WebEngine of JavaFX 2.0 provide a setOnAlert(EventHandler<WebEvent<java.lang.String>> handler); it set EventHandler which will be called when alert() function is called by Javascript inside WebView.

Implement OnAlert EventHandler of WebEngine

Refer to the previous article "Execute JavaScript in WebView from Java code":

- Modify hello.html to add a Javascript pageOnLoad() function to call alert(), and also modify <body> to run pageOnLoad() when page loaded.
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset=utf-8>
<title>Hello Java-Buddy! (from WebPage)</title>

<script>
function updateHello(user){
    document.getElementById("helloprompt").innerHTML="Hello: " + user;
}

function clearHello(user){
    document.getElementById("helloprompt").innerHTML="Hello <a href='http://java-buddy.blogspot.com/'>Java-Buddy</a>";
}

function pageOnLoad(){
    alert();
}
</script>

</head>
<body onload="pageOnLoad()">
<img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjxGfYYk9MPmsy4Fb5yBONPauX59KlswhZvZL_XoWgvPMp2SwHsLorHIo4aWZJsUc9oynuzwstK5MfzjmjmNevnJFjJt1HIhcl-iRH3dnK2twWSeX6MdjSbAz4nyMzaNQE1p-Pajqfg3KKN/s150/duke_44x80.png"/>
<p id="helloprompt">Hello <a href="http://java-buddy.blogspot.com/">Java-Buddy</a></p>
</body>
</html>


- Modify JavaFX code to call setOnAlert() to implement OnAlert EventHandler.
package javafx_webview;

import java.net.URL;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.geometry.VPos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Region;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebEvent;
import javafx.scene.web.WebView;
import javafx.stage.Stage;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFX_Browser extends Application {
    
    private Scene scene;
    MyBrowser myBrowser;

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
    
    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("java-buddy.blogspot.com");
        
        myBrowser = new MyBrowser();
        scene = new Scene(myBrowser, 640, 480);
        
        primaryStage.setScene(scene);
        primaryStage.show();
    }
    
    class MyBrowser extends Region{
        
        HBox toolbar;
        
        WebView webView = new WebView();
        WebEngine webEngine = webView.getEngine();
        
        public MyBrowser(){
            
            final Label labelWebTitle = new Label();
            
            final URL urlHello = getClass().getResource("hello.html");
            webEngine.load(urlHello.toExternalForm());
            
            webEngine.setOnAlert(new EventHandler<WebEvent<String>>(){

                @Override
                public void handle(WebEvent<String> arg0) {
                    labelWebTitle.setText(webEngine.getTitle());
                }

            });
            
            final TextField textField = new TextField ();
            textField.setPromptText("Hello! Who are?");
            
            Button buttonEnter = new Button("Enter");
            buttonEnter.setOnAction(new EventHandler<ActionEvent>(){

                @Override
                public void handle(ActionEvent arg0) {
                    webEngine.executeScript( " updateHello(' " + textField.getText() + " ') " );
                }
            });
            
            Button buttonClear = new Button("Clear");
            buttonClear.setOnAction(new EventHandler<ActionEvent>(){

                @Override
                public void handle(ActionEvent arg0) {
                    webEngine.executeScript( "clearHello()" );
                }
            });
            
            
            toolbar = new HBox();
            toolbar.setPadding(new Insets(10, 10, 10, 10));
            toolbar.setSpacing(10);
            toolbar.setStyle("-fx-background-color: #336699");
            toolbar.getChildren().addAll(labelWebTitle, textField, buttonEnter, buttonClear);
            
            getChildren().add(toolbar);
            getChildren().add(webView);
            
        }
        
        @Override
        protected void layoutChildren(){
            double w = getWidth();
            double h = getHeight();
            double toolbarHeight = toolbar.prefHeight(w);
            layoutInArea(webView, 0, 0, w, h-toolbarHeight, 0, HPos.CENTER, VPos.CENTER);
            layoutInArea(toolbar, 0, h-toolbarHeight, w, toolbarHeight, 0, HPos.CENTER, VPos.CENTER);
        }
        
    }
    
}


Related:
- Communication between JavaFX and JavaScript inside WebView, using JSObject


2 comments:

  1. Thank you for the article.

    But setOnAlert(EventHandler> handler purpose is to set the JavaScript alert handler and you use it for setting the Web page title.

    I am looking for a way to implement setOnAlert to set the JavaScript alert handler. Any help would be welcome.
    JCD

    ReplyDelete