Is CefSharp compatible with JavaScript promises?

I noticed that when I run the JavaScript code below in the console of my browser, it works perfectly fine. However, when I try to use this code in CefSharp, it returns null. I am currently using CefSharp version 100.0.120-pre. Does CefSharp 100.0.120-pre support the promises of JavaScript?

(function()
{
var a = document.querySelector('#dle-content > div.section > ul > li:nth-child(3)');
a.scrollIntoView();
document.querySelector('#dle-content > div.section > ul > li:nth-child(3)').click();    
var returnArray = new Array();
function wait(selector) {
return new Promise((resolve) => {
const listener = () => {
const node = document.querySelector(selector);
if (node) {
document.removeEventListener('DOMNodeInserted', listener);
resolve(node);
}
};
document.addEventListener('DOMNodeInserted', listener);
});
}
wait('.cdn_download_item')
.then(()=>
{
var elements = Array.from(document.querySelectorAll('.cdn_download_item span:first-child'));
var linksArray = new Array();
for (element of elements) 
{
linksArray.push(element.innerText);
}
returnArray=console.log(linksArray);
})
return returnArray;
})();

I am trying to integrate this JavaScript code with CefSharp in C#. Can someone please review my code and help me understand why CefSharp is returning null?

JavaScript + CefSharp + C#

string jsScript = @"
(function()
{
var returnArray = new Array();
function wait(selector) {
return new Promise((resolve) => {
const listener = () => {
const node = document.querySelector(selector);
if (node) {
document.removeEventListener('DOMNodeInserted', listener);
resolve(node);
}
};
document.addEventListener('DOMNodeInserted', listener);
});
}
wait('.cdn_download_item')
.then(()=>
{
var elements = Array.from(document.querySelectorAll('.cdn_download_item span:first-child'));
var linksArray = new Array();
for (element of elements) 
{
linksArray.push(element.innerText);
}
returnArray=console.log(linksArray);
})
return returnArray;
})();
                ";

            var task = chrome.EvaluateScriptAsync(jsScript5);
            await task.ContinueWith(x =>
            {
                if (!x.IsFaulted)
                {
                    var response = x.Result;
                    if (response.Success == true)
                    {
                        var final = (List<object>)response.Result;
                        foreach (var el in final)
                        {
                            textHtml.Text += el.ToString() + Environment.NewLine;
                        }
                    }
                }

            }, TaskScheduler.FromCurrentSynchronizationContext());

Answer №1

Affirmative, promises are indeed supported. Instead of using EvaluateScriptAsync, you need to utilize EvaluateScriptAsPromiseAsync

Executing Javascript within the main frame of this browser is possible. The script will run asynchronously, and the method will return a Task containing the response from the Javascript. The output of the javascript execution is Promise.resolve, so even non-promise values will be handled as promises. Your javascript should have a return value. The script will be enclosed in an Immediately Invoked Function Expression. When the promise triggers either then/catch, the returned Task will be finalized.

EvaluateScriptAsPromiseAsync differs slightly from EvaluateScriptAsync in that a return value is necessary for proper awaiting of the promise.

var script = "return new Promise(function(resolve, reject) { setTimeout(resolve.bind(null, { a: 'CefSharp', b: 42, }), 1000); });"
JavascriptResponse javascriptResponse = await browser.EvaluateScriptAsPromiseAsync(script);

Visit https://github.com/cefsharp/CefSharp/wiki/General-Usage#2-how-do-you-call-a-javascript-method-that-returns-a-result for more examples.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Multiple file uploads are causing the issue of req.file being undefined

After going through all the suggested solutions, I am still struggling to identify the root cause of my issue. The problem arises when trying to upload multiple files and form inputs - the req.file is always undefined and the image data ends up in the req. ...

Concerning the issue of components not loading correctly when using Angular with Lazy Loading Routing

Encountering an unusual issue while utilizing lazyload routing in our application! Within AppModule, there is TopModule followed by DashboardModule, all being loaded lazily. When localhost:4200/dashboard is accessed, the loading sequence is AppModule, To ...

Verifying if any of the entries in a specific index contain a null value

Here is the structure I am working with: { "subs": [ { "status": "1", "run_settings": null, "ward": "/asda/asd/ada" "value": null, "name": null }, { "status": "0", "run_settings": null, "ward": ...

I need assistance with using regex to extract values enclosed in quotes

After spending almost a full day attempting to create a RegEx for a specific string, I have yet to make it work. Can someone offer assistance? string example (double quotes are options, and can also be single quotes): "234"? "<img src=\"http:/ ...

Making an Angular 6 HTTP GET call using HTTP-Basic authentication

When attempting to access a URL that requires Basic Authentication, and returns JSON data, what is the proper way to include my username and password in the following HTTP request? private postsURL = "https://jsonExample/posts"; getPosts(): Observable& ...

Which one relies on the other: angular-data or angular-cache?

I'm struggling to get angular-cache set up properly. According to the documentation: Angular-cache is a dependency of angular-data and must be loaded before angular-data if you are using angular-data. That's all well and good, but what if I only ...

Creating a factory class in Typescript that incorporates advanced logic

I have come across an issue with my TypeScript class that inherits another one. I am trying to create a factory class that can generate objects of either type based on simple logic, but it seems to be malfunctioning. Here is the basic Customer class: cla ...

Troubleshooting problem with custom Angular directive integrating KineticJS

Hey there, I'm currently working on putting together a KineticJS application in Angular and need to resolve a minor issue. While following an example for setting up a draggable shape in AngularJS using KineticJS from this link: , I encountered this er ...

What is the best way to split up the information and place it into separate text boxes?

I am currently working on a page that allows users to create and edit email structures. To facilitate editing, I added two columns to the page. One of the columns displays information from all the email structures along with two buttons - one for editing ...

What causes the Object expected error in jQuery?

Looking for a way to demo horizontal collapse pane with a simple web page that includes html, css, and jquery. <html> <head> <script type="text/javascript" src="//code.jquery.com/jquery-1.10.1.js"></script> <title>Sa ...

Place the div's scrollbar at the beginning of its content

Recently, I put together a custom CSS modal that includes a scrollable div (without the modal itself being scrollable). Interestingly enough, when I initially open the modal, the scrollbar of the div starts at the top as anticipated. However, if I scroll d ...

Is there a way to incorporate locales in calculations involving percentages?

Given the number 4030.146852312 I want to retrieve the four decimal places from this number, resulting in: 4030.1468 Furthermore, I need to format this number according to the specified locale. For example: 4.030,1468 What is the best way to achieve thi ...

Remove an element from an array within objects

Need help with removing specific items from an array within objects? If you want to delete all hobbies related to dancing, you may consider using the splice method const people = [{ id: 1, documents: [{ ...

How can I retrieve the total number of records (count) in an XML response using PostMan?

Hello, I'm currently attempting to determine the length of an XML response but I'm running into some issues. The error message I am encountering is as follows: "There was an error in evaluating the test script: ReferenceError: xml2json is not def ...

Setting up Quill in a Nuxt project (a VUE component)

I'm struggling to remove the toolbar in Quill despite my efforts. This is the HTML snippet I am working with: <template> <quill v-model="content" :config="config"></quill> </template Here's what I have inside the scri ...

The success variable of the Ajax running continuously in a loop is not being refreshed

Within this code snippet, a for loop is utilized to iterate through an array called netnos[] and update the variable 'nets' for each item. Ajax is then invoked to call a PHP script that generates a listing, which is successfully outputted to the ...

Press the designated button located within a table's td element to retrieve the values of adjacent td elements

I need to implement a functionality where clicking a button within a <td> element will retrieve the values of other <td> elements within the same row (<tr>). Here is the current implementation: $(document).ready(function(){ ...

Is there a resource available that can help me create a jquery/ajax image slider/carousel similar to this?

One thing that really caught my eye is how cnn.com has implemented this feature. I think it would be a great addition to the website I'm currently working on. I particularly like the page numbering, as well as the first, previous, next, and last butto ...

How to apply styling to a specific portion of text within a list element using Vue.js

Despite my best efforts, I am struggling to style only the word "healthy" within the 'It is healthy!' string using computed properties, watchers, and methods in vuejs. I'm at a loss for how to achieve this unique styling. <template> ...

Create a heading for the selection menu

I need to customize a dropdown list on my page so that the text "Select Language" is always displayed to the user, regardless of whether they make a selection from the dropdown. Even if the user chooses "Option 1" or "Option 2," the default text should sti ...