Is there any way to catch an error thrown from javascript in cefsharp in my c# program?
Asked Answered
M

1

5

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 ?

Manage answered 23/7, 2019 at 23:5 Comment(2)
No, you cannot catch errors through ExecuteJavaScriptAsync, you have to use EvaluateScriptAsyncArvy
And how can I do it with EvaluateScriptAsync() (catch the error ) could you give me an example on how you would do it ? @ArvyManage
C
7

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());
Chanukah answered 23/7, 2019 at 23:15 Comment(5)
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 ? @ArvyManage
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.