Reputation: 1443
I would like to catch and log any JavaScript errors or Warnings from pages I host in a WebView inside my UWP app.
I would like to be able to catch these errors for any webpage I load in my app's WebView.
I know that Visual Studio has a mechanism to attach to a UWP apps' WebView and log the JavaScript errors, but I would like to do the same without Visual Studio.
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.
If possible, I would like to have something similar to the JavaScript console in F12 tools, but I at least need to be able to get JavaScript errors and warnings.
Upvotes: 1
Views: 2871
Reputation: 8591
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 });
}
Upvotes: 1