NativeWebView Manual
HTML windows from PowerShell 7
This manual shows how to install NativeWebView and use it in your scripts. The introduction and the features demo show it in action.
Prerequisites
- PowerShell 7.2 or later. Windows PowerShell 5.1 is not supported.
- Windows 10/11: the WebView2 runtime, which is included in Windows 11 and installed with Microsoft Edge on Windows 10.
- Linux: the WebKitGTK library libwebkit2gtk-4.1 (on Debian and Ubuntu:
sudo apt install libwebkit2gtk-4.1-0).
If no web engine is found, the page opens in an Edge or Chrome app window, or in the default browser.
Steps
- Open PowerShell 7 and install the module from the PowerShell Gallery:
Install-PSResource NativeWebView
- Show a page with one line of PowerShell:
Show-NativeWebView -Html '<h1>Hello from PowerShell</h1>' -Title 'Hello'
The window opens with the heading and its own title. The call waits until you close the window, like a dialog,
and then the script continues.
- Let the page talk to the script. The page gets a
kHost object, and kHost.send sends
a JSON object to the -OnMessage block. The fields of the message are properties of $Message:
$Html = @'
<button onclick="kHost.send({action:'greet', name:'Ada'})">Greet</button>
<p id="out"></p>
<script>kHost.on(function (m) { document.getElementById('out').textContent = m.text; });</script>
'@
Show-NativeWebView -Html $Html -OnMessage {
param($Message, $Window)
$Window.Send('reply', @{ text = "Hello, $($Message.name)" })
}
- Answer the page with
$Window.Send, and use $Window.Close() when the script should
close the window.
- When the page needs an answer, use
kHost.call instead of kHost.send. It waits for the
script, and what the -OnMessage block outputs comes back to the page:
$Html = '<button onclick="kHost.call(''time'').then(function (t) { document.body.append(t) })">Time</button>'
Show-NativeWebView -Html $Html -OnMessage {
param($Message)
if ($Message.action -eq 'time') { (Get-Date).ToString('T') }
}
- Let a dialog return its answer. The page closes the window with
kHost.close(result), and
Show-NativeWebView returns the result as an object:
$Html = '<input id="n"><button onclick="kHost.close({ name: n.value })">OK</button>'
$Answer = Show-NativeWebView -Html $Html -Title 'Your name'
"Hello $($Answer.name)"
- If you wish to keep the page in a file, use
-Path page.html instead of -Html.
More info
|