Communicating with Javascript in a Web View

MoneyWorks 9.1 provides modernised web views on Mac and Windows (see New Web Views in MoneyWorks 9.1). MoneyWorks 9.1 and later also provides new functionality for communicating with the content of web views (requires WebView2 Runtime on Windows).

Calling out to MWScript from Javascript in the web page

You can now call a MWScript handler from javascript in a web page hosted in the Web View, passing it a JSON parameter. You need to set up the callable handler in advance using WebViewControl

MWScript to install an observer handler that can be called from Javascript
on Before:MyWindow(w)
    // L_WEB is the identifier of your web view control
    WebViewControl(w, "L_WEB", "options addObserver='MyHandlerName'")
end

on MyHandlerName(data)
   say(data) // might want to actually parse the JSON using JSON_Parse
end
Javascript to call the observer handler
var message = { // Some JSON to send to the handler
    name: document.getElementById("name").value,
    email: document.getElementById("email").value
    };

// Of course the javascript is different depending on Webkit/Chrome :-(
var ischrome = /Chrome/.test(navigator.userAgent);
if(ischrome)
    window.chrome.webview.postMessage(message); // Windows case
else
    window.webkit.messageHandlers.MyHandlerName.postMessage(message); // Mac case

Note that with WebKit on the Mac, you can install multiple "observer" handlers and call any of them by name using window.webkit.messageHandlers.YOUR_HANDLER_NAME.postMessage. With Chrome on Windows, you can only install one, that will be called by window.chrome.webview.postMessage

Injecting javascript into the web page from MWScript

You can execute some javascript in the web view and be called back with the result

WebViewControl(winhdl, "L_WEB", "evaluate", javascript, "CompletionHandler")

The CompletionHandler is a MWScript handler that will be called when the javascript finishes executing. It will receive as a parameter the last value evaluated by the javascript.

on CompletionHandler(javaScriptResult)
   // ....
end

Injecting one line of javascript to get the value of an input field

WebViewControl(winhdl, "L_WEB", "evaluate", `document.getElementById("name").value;`, "CompletionHandler")

Note that javascript injection should not be attempted until after the html is loaded.

Posted in Uncategorized | Comments Off on Communicating with Javascript in a Web View