New WebView APIs for Solar2D(iOS/macOS/Android)

We’ve extended the WebView API with new methods and events to make it more powerful.

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
     <script>
        window.onNativeBridgeReady = function() {
            console.log("NativeBridge is ready!");
            updateDeviceInfo();  
        }
    </script>
</head>
<body>
    <div id="deviceInfo"></div>
    <button id="updateButton">Update Info</button>
    <button id="greetButton">Greet</button>
    <div id="response"></div>
</body>
</html>
local json = require("json")

local webView = native.newWebView(
    display.contentCenterX,
    display.contentCenterY,
    display.actualContentWidth,
    display.actualContentHeight
)

webView:registerCallback("getDeviceInfo", function()
    return {
        platform = system.getInfo("platform"),
        version = system.getInfo("architectureInfo"),
        language = system.getPreference("locale", "language"),
        deviceModel = system.getInfo("model")
    }
end)

webView:on("buttonClicked", function(data)
    webView:send("buttonResponse", {message = "Received click for button " .. data.buttonId})
end)

local function injectJS()
    webView:injectJS[[
    function updateDeviceInfo() {
        NativeBridge.callNative("getDeviceInfo").then(info => {
            document.getElementById("deviceInfo").innerHTML = 
                `Platform: ${info.platform}<br>
                 Version: ${info.version}<br>
                 Language: ${info.language}<br>
                 Model: ${info.deviceModel}`;
        });
    }

    ["updateButton", "greetButton"].forEach(id => {
        document.getElementById(id).addEventListener('click', () => {
            if(id === "updateButton") updateDeviceInfo();
            NativeBridge.sendToLua("buttonClicked", {buttonId: id.replace("Button", "")});
        });
    });

    NativeBridge.on("buttonResponse", data => {
        document.getElementById("response").textContent = data.message;
    });
    ]]
end

webView:request("index.html", system.ResourceDirectory)
webView:addEventListener("urlRequest", function(event)
    if event.type == "loaded" then injectJS() end
end)
9 Likes

Are there any special challenges with Windows, since you list “iOS / MacOS / Android”?

I’m curious if you’ve tried it with any wasm-heavy libraries, e.g. for something like this (except for the QuickJS / txiki.js paragraph, for doing this in native). Seems like the new APIs could open the door for such libraries—or transpiling C, C++, etc. projects.

  1. Windows presents no specific challenges; it’s just not been prioritized yet.
  2. We haven’t experimented with wasm-heavy libraries. You can search to see if there are any discussions about this in Cordova.
1 Like