B4J Question Capturing confirm dialogs in webview

Teleboy20

New Member
Licensed User
Longtime User
Hello all,

After much reading of the forum and javadocs, I've come to the conclusion that I have no clue how to capture dialogs from a webview. I've been trying to utilize setConfirmDialog, but haven't had any success. I'm using a javaobject with the webengine to run the method, but am unsure what steps are needed (creat e an event, callbacks etc.). Any assistance is greatly appreciated. Sample code would be even better.

Thanks in advance, RickT
 

Daestrum

Expert
Licensed User
Longtime User
Small example that handles a button on a web page that calls window.confirm() routine.
needs JavaObject Library
The handler setting and dialog display handled in pure java.

Hope it helps.


B4X:
Sub Process_Globals
    Private fx As JFX
    Private MainForm As Form
    Dim wv As WebView
End Sub

Sub AppStart (Form1 As Form, Args() As String)
    MainForm = Form1
    MainForm.SetFormStyle("UNIFIED")
    'MainForm.RootPane.LoadLayout("Layout1") 'Load the layout file.
    wv.Initialize("")
    MainForm.Show
    MainForm.RootPane.AddNode(wv,10,10,100,100)
    ' call the inline java
    ' with webview as the argument
    inLine("setConfHandler",Array(wv))
    ' load the htnl - just a button that calls window.confirm()
    wv.LoadHtml($"<html><input type="button" width="200" value="Confirm Test" onclick="window.confirm()"></html>"$)
End Sub
Sub inLine(method As String,Args() As Object)
    asJO(Me).RunMethod(method,Args)  
End Sub
Sub asJO(o As JavaObject)As JavaObject
    Return o
End Sub
#if java
import javafx.util.Callback;
import javafx.scene.web.WebView;
import javafx.scene.web.WebEngine;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import java.util.Optional;
import javafx.scene.control.ButtonType;

// set the handler
public static void setConfHandler(WebView wv){
    WebEngine we = wv.getEngine();
    we.setConfirmHandler(new Callback<String, Boolean>() {
       @Override public Boolean call(String msg) {
          Boolean confirmed = confirm();
          return confirmed;
           }
      });
}
//show the dialog box
private static boolean confirm(){
    Alert alert = new Alert(AlertType.CONFIRMATION);
    alert.setTitle("Confirmation Dialog");
    alert.setHeaderText("Look, a Confirmation Dialog");
    alert.setContentText("Are you ok with this?");

    Optional<ButtonType> result = alert.showAndWait();
    if (result.get() == ButtonType.OK){
       return true;
    } else {
       return false;
    }
}
#end if
 
Upvote 0

Teleboy20

New Member
Licensed User
Longtime User
Thank you so much Daestrum! That plugged into my code perfectly. Now to study what you've done. Thanks again.
 
Upvote 0
Top