JavaFX WebEngine run Javascript

Description

JavaFX WebEngine run Javascript

import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Worker.State;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;

public class Main extends Application {
   public static void main(String[] args) {
      Application.launch(args);//from w w w.j a v  a  2 s  .co  m
   }

   @Override
   public void start(Stage primaryStage) {
      VBox vb = new VBox();
      vb.setId("root");

      WebView browser = new WebView();
      WebEngine engine = browser.getEngine();
      String url = "https://demo2s.com/java/javafx-lineargradient-create.html";
      engine.load(url);

      engine.getLoadWorker().stateProperty().addListener(new ChangeListener<State>() {
         public void changed(ObservableValue<? extends State> observable, State oldValue, State newValue) {

            if (newValue != State.SUCCEEDED) {
               return;
            }
            engine.executeScript("document.getElementById('sidebar').innerHTML = 'new value'");
            System.out.println("done!" + newValue.toString());
         }
      });

      vb.setPadding(new Insets(30, 50, 50, 50));
      vb.setSpacing(10);
      vb.setAlignment(Pos.CENTER);
      vb.getChildren().addAll(browser);

      Scene scene = new Scene(vb);
      primaryStage.setScene(scene);
      primaryStage.show();
   }
}



PreviousNext

Related