This answer for JavaScript error handling shows how to do this in plain JavaScript, but I need to know how and when to inject code like this into a WebView, or if there is a better way to do this.
You could try to use InvokeScriptAsync with the JavaScript eval
function to inject content into the web page when Navigation Completed.
Then, if you want to get the error message in your app, you could use window.external.notify
with a string parameter to send information back to your app. To receive these messages, handle the ScriptNotify event.
I made a simple code sample for your reference:
<!DOCTYPE html>
<!--this is my local web page HTMLPage1.html-->
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<script type="text/javascript">
function test() {
}
</script>
</head>
<body>
<input value="click" onclick="test1()" type="button"/>
</body>
</html>
<WebView x:Name="webview" NavigationCompleted="webview_NavigationCompleted" ScriptNotify="webview_ScriptNotify" Source="ms-appx-web:///HTMLPage1.html"></WebView>
private void webview_ScriptNotify(object sender, NotifyEventArgs e)
{
string msg = e.Value;
}
private async void webview_NavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)
{
string functionString = "window.onerror = function(error, url, line) {window.external.notify( 'ERR:'+error+' url'+url+' Line: '+line);};";
var ret = await webview.InvokeScriptAsync("eval", new string[] { functionString });
}