B4J Code Snippet Running JS expressions on the fly

William Lancee

Active Member
Licensed User
In trying to solve another problem I stumbled into what might be useful to others.
It seems to be the minimum required to run scripts on the fly.

I have attached a project "CodeRunner" that uses this method. It extends this snippet to run B4X code on the fly. This is done in about 500 lines of code, without external libraries. CodeRunner was inspired by a question from @B4JExplorer and answer by @Cableguy, see:


Sub Process_Globals
    Private fx As JFX
    Private MainForm As Form
    Private WebView1 As WebView
    Private jo As JavaObject
    Private joEngine As JavaObject
End Sub

Sub AppStart (Form1 As Form, Args() As String)
    MainForm = Form1                    'For this demonstration we don't need to see the form, but because of webview this is an UI app
    MainForm.RootPane.AddNode(WebView1, .4*MainForm.WindowWidth, .4*MainForm.WindowHeight, .6*MainForm.WindowWidth, .6*MainForm.WindowHeight)
    jo = WebView1
    joEngine = jo.RunMethodJO("getEngine", Null)
    Dim expressions() As String = Array As String ( _
            $""\"extra quoted\"""$, _
            "'xxx' + 'yy'", _
            "'13 Mod 7 is ' + 13 % 7", _
            "true == false", _
            "'Pi is ' + Math.PI", _
            "'The\nEnd'" _
    Dim theResult As String
    For j = 0 To 5
        theResult = runScript(expressions(j))
        Log(theResult & CRLF & "_____")

End Sub

Sub runScript(s As String) As String
    Return joEngine.RunMethod("executeScript", Array As String(s))
End Sub
Edit (after @Kiffi 's like :)): I just found this relevant link, thanks to @Kiffi




Last edited: