Tuesday, March 27, 2012

Execute JavaScript in WebView from Java code

JavaFX WebView provide a executeScript() method, it can execute Javascript in html code currently loaded in WebView.

Execute JavaScript in WebView from Java code

It's a example demonstrate how to call Javascript function with and without parameter passed, from Java code.

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.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Region;
import javafx.scene.web.WebEngine;
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 URL urlHello = getClass().getResource("hello.html");
          webEngine.load(urlHello.toExternalForm());
        
          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(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);
      }
    
  }

}


hello.html
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset=utf-8>
<title>Hello Java-Buddy!</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>";
}
</script>

</head>
<body>
<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>


Related:
- OnAlert EventHandler of WebEngine.
- Communication between JavaFX and JavaScript inside WebView, using JSObject.


2 comments:

  1. how can i pass java object to execute script

    e.g
    i have
    Person p = new Person();
    .......
    .....

    following is not working
    webEngine.executeScript("add(" + p + ")");

    ReplyDelete
  2. Can I deploy this as cross platform app?

    ReplyDelete