JavaFX How to - Check if JavaFX application is launched from desktop or web browser








Question

We would like to know how to check if JavaFX application is launched from desktop or web browser.

Answer

// w  ww.jav  a 2  s  .  com
import javafx.application.Application;
import javafx.application.HostServices;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import netscape.javascript.JSObject;

public class Main extends Application {
  public static void main(String[] args) {
    Application.launch(args);
  }

  @Override
  public void start(Stage stage) {

    Button openURLButton = new Button("Go!");
    openURLButton.setOnAction(e ->{
      HostServices host = getHostServices();
      JSObject js = host.getWebContext();
      if (js == null) {
          Stage s = new Stage(StageStyle.UTILITY);
          s.initModality(Modality.WINDOW_MODAL);
          Label msgLabel = new Label("This is an FX alert!");
          Group root = new Group(msgLabel);
          Scene scene = new Scene(root);
          s.setScene(scene);
          s.setTitle("FX Alert");
          s.show();
      } else {
          js.eval("window.alert('This is a JavaScript alert!')");
      }      
    });

    Scene scene = new Scene(openURLButton);
    stage.setScene(scene);
    stage.setTitle("Knowing the Host");
    stage.show();
  }
}