examples/08-Call.ps1

# 08 - Call: the page asks PowerShell with kHost.call and awaits the answer - what -OnMessage outputs comes back.
if (-not (Get-Command Show-NativeWebView -ErrorAction Ignore)) { Import-Module NativeWebView -ErrorAction Stop }

$Html = @'
<!doctype html>
<html><head><style>
  body { font-family: Verdana, 'Segoe UI', Arial, sans-serif; font-size: 13px; color: #454545; padding: 24px; background: #F9F9F9; }
  h2 { color: #154363; font-size: 18px; }
  button { padding: 8px 18px; background: #095495; color: white; border: 0; border-radius: 4px; font: inherit; margin-right: 8px; }
  button:hover { background: #154363; }
  table { border-collapse: collapse; width: 100%; margin-top: 14px; background: white; }
  td, th { border: 1px solid #CCCCCC; padding: 4px 8px; text-align: left; }
  th { background: #154363; color: white; }
  #out { margin-top: 10px; color: #4F8035; }
</style></head>
<body>
  <h2>Top processes</h2>
  <button id="ask">Ask PowerShell</button>
  <button id="done">Done</button>
  <div id="out">-</div>
  <table><thead><tr><th>Name</th><th>Memory (MB)</th></tr></thead><tbody id="rows"></tbody></table>
  <script>
    document.getElementById("ask").onclick = async function () {
      var count = 5;
      var list = await kHost.call("top", { count: count });
      var rows = document.getElementById("rows");
      rows.innerHTML = "";
      list.forEach(function (p) {
        var tr = document.createElement("tr");
        tr.innerHTML = "<td></td><td></td>";
        tr.children[0].textContent = p.name;
        tr.children[1].textContent = p.mb;
        rows.appendChild(tr);
      });
      var info = await kHost.call("engine");
      document.getElementById("out").textContent = list.length + " processes, shown by " + info;
    };
    document.getElementById("done").onclick = function () { kHost.close(null); };
  </script>
</body></html>
'@


Show-NativeWebView -Html $Html -Title "Call" -Width 520 -Height 420 -OnMessage {
    param($Message, $Window)
    switch ($Message.action) {
        # A list comes back to the page as a JSON array of objects.
        "top" {
            ,@(Get-Process | Sort-Object WorkingSet64 -Descending | Select-Object -First $Message.count |
                ForEach-Object { @{ name = $_.ProcessName; mb = [math]::Round($_.WorkingSet64 / 1MB) } })
        }
        "engine" { $Window.Engine() }
    }
}