'Synchronous JavaScript calls with CefSharp
I have to modify a project (C#) that uses CefSharp to automate a web task. Each time the code needs to execute a piece of Javascript, it uses:
browser.ExecuteScriptAsyncWhenPageLoaded(script);
But now I have cases where Javascript has to be executed synchronously, that is:
ExecuteScript(script1);
[wait for script1 to complete]
[do some stuff]
ExecuteScript(script2);
[etc]
So, is there a way to make a synchronous Javascript call in CefSharp?
Solution 1:[1]
The browser is fundamentally async, JavaScript runs in a separate process. You can await the async calls.
private async void Button_Click(object sender, EventArgs e)
{
string jsScript1 = "1 + 1";
JavascriptResponse response1 = await browser.EvaluateScriptAsync(jsScript1);
var onePlusOne = (int)response1.Result;
// Do some work here.
// If your JavaScript results in a navigation then you can use WaitForNavigationAsync to wait for the page to load, see example below
string jsScript2 = "some java script code";
JavascriptResponse response2 = await browser.EvaluateScriptAsync(jsScript2);
}
Some more common usage examples.
//An extension method that evaluates JavaScript against the main frame.
JavascriptResponse response = await browser.EvaluateScriptAsync(script);
//Evaluate javascript directly against a frame
JavascriptResponse response = await frame.EvaluateScriptAsync(script);
//An extension method that evaluates Javascript Promise against the main frame.
//Uses Promise.resolve to return the script execution into a promise regardless of the return type
//This method differs from EvaluateScriptAsync in that your script **must return** a value
//Examples below
JavascriptResponse response = await browser.EvaluateScriptAsPromiseAsync(script);
//JavaScript that results in a navigation.
var navigationTask = browser.WaitForNavigationAsync();
var evaluateTask = browser.EvaluateScriptAsync($"window.location.href = 'github.com';");
await Task.WhenAll(navigationTask, evaluateTask);
var navigationResponse = navigationTask.Result;
For those new to CefSharp I'd also suggest reading https://github.com/cefsharp/CefSharp/wiki/General-Usage#javascript-integration
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | amaitland |
