Say for example that I am running a script through cefSharp using the ExecuteJavaScriptAsync(..) method and that an error is thrown while running the script, how can I detect it and then catch it in my c# program ?
Is there any way to catch an error thrown from javascript in cefsharp in my c# program?
Asked Answered
No, you cannot catch errors through ExecuteJavaScriptAsync, you have to use EvaluateScriptAsync –
Arvy
And how can I do it with EvaluateScriptAsync() (catch the error ) could you give me an example on how you would do it ? @Arvy –
Manage
If you need to evaluate code which returns a value, use the Task EvaluateScriptAsync(string script, TimeSpan? timeout) method. Javascript code is executed asynchronously and as such uses the .Net Task class to return a response, which contains error message, result and a success (bool) flag.
// Get Document Height
var task = frame.EvaluateScriptAsync("(function() { var body = document.body, html = document.documentElement; return Math.max( body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight ); })();", null);
task.ContinueWith(t =>
{
if (!t.IsFaulted)
{
var response = t.Result;
EvaluateJavaScriptResult = response.Success ? (response.Result ?? "null") : response.Message;
}
}, TaskScheduler.FromCurrentSynchronizationContext());
I do not just want to evaluate code but catch errors,is there any way to do that ? –
Manage
If you want to get the error then you will have to use EvaluateScriptAsync. –
Arvy
And how can I do it with EvaluateScriptAsync() (catch the error ) could you give me an example on how you would do it ? @Arvy –
Manage
You need to return a response from your javascript code. Response can contain error message. Check if response contains error message and do whatever you like with it from there,you can throw the same error in c# –
Chanukah
For reference see cefsharp.github.io/api/73.1.x/html/… the answer given is valid. –
Arvy
© 2022 - 2024 — McMap. All rights reserved.