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

Top method for enhancing outside libraries in AngularJs

Currently, I am utilizing the angular bootstrap ui third party library as a dependency in my angular application. One question that is on my mind is what would be the most effective method to enhance the functionality of directives and controllers within t ...

Tips for concealing select options after choosing with select picker?

Our establishment features three distinct rooms, each offering three identical options that users can choose from. https://i.sstatic.net/Jx4Me.png To illustrate, if a user named John selects option one in the first room, that same option will be hidden w ...

Checking the image loading functionality with Cypress

I am interested in testing Cypress to verify that an image is successfully loaded onto a page. Here is a snippet of my source code: import React from "react"; export default class Product extends React.Component { render() { return ( <div ...

401 error code for all CRUD operations in the .NET Framework API

So, I've been working on a project that consists of a .Net framework API and an Angular frontend. I recently implemented OWIN JWT authentication, but now I'm encountering a persistent 401 error no matter what I try. I've attempted numerous ...

How to accurately incorporate the "HH:MM" time format into a Date Object in JavaScript

I need to convert a specific time of the day into a Date Object. The time is in String format and is in CET (Central European Time). In CET, "16:00" translates to "15:00" in UTC during Winter time. The code snippet below achieves this conversion in node.js ...

What is the most effective method for establishing functions in AngularJS?

Hey there, I'm currently working on a function in AngularJS and I'm not sure what the best practice is for defining methods. Any suggestions would be greatly appreciated. Option 1: var getBranchKey = function(currentBranchName) { }; Option 2: ...

using VueJS, learn how to dynamically apply text to a data variable based on certain props

I'm facing an issue with conditional value assignment to the data variable based on props. The ternary operator is causing errors in my code. Here's a snippet for reference: <template> <div class="absolute left-3 top-1/2"> ...

Using jQuery AJAX to send data containing symbols

When making an AJAX call, I am including multiple values in the data like this: var postData = "aid="+aid+"&lid="+lid+"&token="+token+"&count="+count+"&license="+license; postData = postData + "&category="+category+"&event_name="+e ...

Dynamically remove values from other fields in a React Formik form based on checkbox conditions

Currently, I am utilizing react-formik for my form implementation. I have encountered an issue with checkbox-based conditions where the checked status of a checkbox determines whether two hidden fields are displayed or hidden. If the user checks the checkb ...

How can we trigger the Skill bar effect upon scrolling to the section?

I have created a stunning Skill Bar that is functioning perfectly. However, I am looking to enhance the experience by having the skill bar effect trigger only when I scroll to that specific section. For example, as I navigate from the introduction section ...

Remove a file using Mongoose and Express by simply pressing a button

Trying to delete a connected account using Express and Mongoose. When the user clicks on a button (confirming their desire to delete their account), I want their account to be removed from my user's collection. HTML code snippet: <div class=" ...

Experiencing difficulties with loading Facebook wall feed JSON data

Struggling to integrate a Facebook wall feed using jQuery on my website's client side. Utilizing this URL for the Facebook request: Attempted approaches so far: 1. $.getJSON('http://www.facebook.com/feeds/page.php?format=json&id=407963083 ...

having difficulty applying border color to input when clicked

Is there a way to change the border color of an input field on an onClick event? In my scenario, if the 'Other' radio button is selected and a user attempts to save without entering any value in the input field, I want the border color of the in ...

Exploring Checkbox Limiting with jQuery

Is there a more efficient approach to restrict the selection of checkboxes? I want the script to be adaptable depending on the applied class, which will always indicate the maximum allowed value (e.g., "limit_1" or "limit_2"). Currently, I'm creatin ...

What is the correct process for authenticating requests from SSR to the Feathers JS API?

There are some examples available on how to access FeathersJS API from SSR, but the important aspect of authorizing such requests is missing. Is it feasible to create a feathers-client app for each request? Wouldn't that put too much load on the syste ...

Scraping a few URLs with Javascript for Web Data Extraction

I'm struggling to retrieve data from multiple URLs and write it to a CSV file. The problem I'm facing is that the fetched data is not complete (I expect 10 items) and it's not in the correct order. Instead of getting 1, 2, 3 sequentially, I ...

You won't find the property 'includes' on a type of 'string[]' even if you're using ES7 features

I encountered a similar issue on another page where it was suggested to modify the lib in tsconfig.josn. However, even after changing compile to es7, the same error kept appearing and the project couldn't be compiled or built. { "compileOnSave": ...

React approach for managing multiple combobox values

Currently, I'm working on a page where users can upload multiple files and then select the file type for each file from a dropdown menu before submitting. These 'reports' are the uploaded files that are displayed in rows, allowing users to c ...

Uncovering data from a dynamic website through the combination of Selenium and PhantomJS

I am attempting to obtain the timer value from this website http://prntscr.com/kcbwd8 located at , and ideally save it in a variable. import urllib from bs4 import BeautifulSoup as bs import time import requests from selenium import webdriver from urllib. ...

"Identifying the exact number of keys in a JSON object using

Is there a key in the JSON data that may or may not exist? How can I determine the total number of occurrences of this key using jQuery? JSON : jasonData = [{"test":"sa3"},{"test":"4s"},{"acf":"1s"},{"test":"6s"}]; I need assistance with implementing th ...