Two way communication for WebViews

Hi all, just wanted to share a quick technique I just descoverd to achieve somewhat a two way communication with your scriptable webviews. Basically having the ability to call scriptable functionality or send data from inside your webviews.

On your scriptable script you would have code similar to this:

const wv = new WebView();
function watcher() {
    wv.evaluateJavaScript(`console.log('watcher activated...');`, true).then((res) => {
        console.log('response: ' + res);
        // Do stuff here with the data passed from inside the webview script. Maybe 
        // save the data to a file for a simple storage mechanism.
        watcher(); // Call the watcher again to continue listening for any data sent from the webview. 
    });
}
wv.loadHTML(htmlSource);
watcher();
wv.present(true);

Then on the script inside your webview. You can send data by calling the completion() function.

function sendData() {
     completion(JSON.stringify(APP_DATA));
}

You can repeatedly call the sendData() function to send data to the outside listening scriptable script.

Now for sending data from scriptable to your webview script.

wv.evaluateJavaScript(`window.onScriptableMessage(${{data: '<any data you want to pass to the webview>'}})`);

Then you would set a listener inside your webview script like this…

window.onScriptableMessage = (data) => {
     console.log(data); //Data from scriptable
};

Anyone tried a similar technique? Or has a more efficient way to achieve this?

Cheers

4 Likes

Your method is probably better than mine, but at the time of posting mine, the WebView.evaluatJavaScript function did not have the ability for the completion callback.

1 Like

Yeah I’ve seen your post. It is actually the one that gave me the idea/insperation for the technique I posted. I tried it but the webview’s shouldAllowRequest function but was a bit of a pain to deal with in my experience :sweat_smile: