Javascript in JavaFX WebView

I'm new to Java and JavaFX, and I'm just wondering if JavaFX web browsing can run javascript on its own, apart from communicating with it using java code. Can I, for example, trigger a javascript alert in webview when a window loads and actually receives a warning in a web browser, like in a regular browser. I know that I can capture this alert event with my java code

webEngine.setOnAlert

but I really want javascript events to occur in the webview itself, as in a normal browser.

The reason I ask this simple question is because I use webview with a text box where I want to enable spell checking. I have a javascript spell checker that works fine in regular browsers where I get a red underline when I type something incorrectly, but I want to make it work in JavaFX webview too.

I am grateful for any help I can get!

+7
java javascript javafx webview
source share
1 answer

WebView JavaScript Callback Handler Example

Here is some sample code to display a JavaFX dialog based on a JavaScript launch command. The sample code is for the JavaScript acknowledgment handler, but the code for the alert handler will work the same way.

In the screenshot of the example, a JavaFX label will appear on the yellow bar on the basis of the result of the confirmation dialog box called up by the JavaScript function called from WebView, which covers the rest of the screen.

A confirmation dialog is displayed in JavaFX on top of the WebView, preventing interaction with the WebView when the dialog is displayed. The style of the confirmation dialog is just a sample, it can be in any way you want to use css, and the layout can also be changed in the code (or you could determine the location of the dialog in the FXML markup, if you want).

webviewconfirm

WebViewConfirm.java

 import javafx.application.Application; import javafx.beans.property.BooleanProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.event.*; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.effect.BoxBlur; import javafx.scene.input.MouseEvent; import javafx.scene.layout.*; import javafx.scene.paint.Color; import javafx.scene.web.WebView; import javafx.stage.*; import javafx.util.Callback; /** * Demonstrates a modal WebView confirm box in JavaFX. * Dialog is rendered upon a blurred background. * Dialog is translucent. * Requires JavaFX 2.2 * To test, run the program, then click the "Try it" button in the Result textarea. */ public class WebViewConfirm extends Application { public static void main(String[] args) { launch(args); } @Override public void start(final Stage primaryStage) { // initialize the stage primaryStage.setTitle("Modal Confirm Example"); final WebView webView = new WebView(); webView.getEngine().load("http://www.w3schools.com/js/tryit.asp?filename=tryjs_confirm"); // layout the stage - a vbox to show confirmation results and a webview to generate confirmations. final VBox confirmationResults = new VBox(); confirmationResults.getStyleClass().add("confirmation-results"); confirmationResults.setMinWidth(150); HBox layout = new HBox(); layout.getChildren().addAll(confirmationResults, webView); primaryStage.setScene(new Scene(layout)); primaryStage.show(); primaryStage.getScene().getStylesheets().add(getClass().getResource("modal-dialog.css").toExternalForm()); // show the confirmation dialog each time a new page is loaded and // record the confirmation result. webView.getEngine().setConfirmHandler(new Callback<String, Boolean>() { @Override public Boolean call(String msg) { Boolean confirmed = confirm(primaryStage, msg); confirmationResults.getChildren().add(new Label("Confirmed? " + confirmed)); return confirmed; } }); } private Boolean confirm(final Stage parent, String msg) { final BooleanProperty confirmationResult = new SimpleBooleanProperty(); // initialize the confirmation dialog final Stage dialog = new Stage(StageStyle.TRANSPARENT); dialog.initOwner(parent); dialog.initModality(Modality.WINDOW_MODAL); dialog.setScene( new Scene( HBoxBuilder.create().styleClass("modal-dialog").children( LabelBuilder.create().text(msg).build(), ButtonBuilder.create().text("OK").defaultButton(true).onAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent actionEvent) { // take action and close the dialog. confirmationResult.set(true); parent.getScene().getRoot().setEffect(null); dialog.close(); } }).build(), ButtonBuilder.create().text("Cancel").cancelButton(true).onAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent actionEvent) { // abort action and close the dialog. confirmationResult.set(false); parent.getScene().getRoot().setEffect(null); dialog.close(); } }).build() ).build() , Color.TRANSPARENT ) ); // allow the dialog to be dragged around. final Node root = dialog.getScene().getRoot(); final Delta dragDelta = new Delta(); root.setOnMousePressed(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent mouseEvent) { // record a delta distance for the drag and drop operation. dragDelta.x = dialog.getX() - mouseEvent.getScreenX(); dragDelta.y = dialog.getY() - mouseEvent.getScreenY(); } }); root.setOnMouseDragged(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent mouseEvent) { dialog.setX(mouseEvent.getScreenX() + dragDelta.x); dialog.setY(mouseEvent.getScreenY() + dragDelta.y); } }); // style and show the dialog. dialog.getScene().getStylesheets().add(getClass().getResource("modal-dialog.css").toExternalForm()); parent.getScene().getRoot().setEffect(new BoxBlur()); dialog.showAndWait(); return confirmationResult.get(); } // records relative x and y co-ordinates. class Delta { double x, y; } } 

modal-dialog.css

 /** * modal-dialog.css * place in same directory as WebViewConfirm.java * ensure your build system copies the file to your build output directory */ .root { -fx-glass-color: rgba(95, 158, 160, 0.9); } .modal-dialog { -fx-padding: 20; -fx-spacing: 10; -fx-alignment: center; -fx-font-size: 20; -fx-background-color: linear-gradient(to bottom, derive(-fx-glass-color, 20%), -fx-glass-color); -fx-border-color: derive(-fx-glass-color, -20%); -fx-border-width: 5; -fx-background-insets: 12; -fx-border-insets: 10; -fx-border-radius: 6; -fx-background-radius: 6; } .modal-dialog:pressed { -fx-cursor: move; } .modal-dialog .button:pressed { -fx-cursor: default; } .confirmation-results { -fx-background-color: cornsilk; -fx-padding: 5; } 

Possible answer to your question

Your question is not entirely clear, but I think that if you open the ControlsFX dialog box, you will achieve what you want. You can use either the standard dialog (which works like an Internet Explorer warning dialog box) or the lightweight dialog (which works like a JavaScript warning dialog in JavaScript) - see ControlsFX for more information.

ControlsFX is based on Java 8, but for JavaFX 2.2 there are many topics in StackOverflow regarding displaying dialogs in JavaFX (for example: How to create and display a general dialog (Error, Warning, Confirmation) in JavaFX 2.0? ). The sample code above is an example of using the dialog in JavaFX 2.2

Comments on additional questions raised in your question

if JavaFX webview can run javascript on its own, except what it has with java code

Yes, WebView can handle JavaScript.

Can I, for example, run an instruction to warn javascript in webview when a window loads and actually receives a warning in a web browser, like in a normal browser.

Yes, if you set up an alert handler for your WebView to function as a “normal browser,” a dialog box appears when you receive a JavaScript alert command. Note that “regular browsers” do not change the object model of a web page document based on the JavaScript alert function, instead they exit their own dialog — the dialog is not part of the web page.

I really want javascript events to occur in the webview window itself, as in a normal browser.

“Normal” browsers handle alerts differently depending on the user interface model. For example, in Firefox, a warning dialog box appears in the current browser tab window, and in Internet Explorer a warning window appears above the Internet Explorer window. The JavaFX alert handler is flexible enough to handle the alert, but you want to.

+10
source share

All Articles