CefSharp - The C# method is returning unexpected data to JS

I'm facing an issue with the data being returned from C# to JS. Here is my CefSharp configuration:

        Cef.Initialize();
        CefSharpSettings.WcfEnabled = true;
        CefSharpSettings.LegacyJavascriptBindingEnabled = true;
        browser = new ChromiumWebBrowser("")
        {
            Dock = DockStyle.Fill
        };
        this.Controls.Add(browser);
        SM = new ScriptManager(browser);
        browser.RegisterAsyncJsObject("external", SM); //"Support" for C# methods from JavaScript

I am attempting to call a C# method from JS:

...
var UserID_array = window.external.loadUsrIDs(usr_names); //usr_name -> array of user names

In C#, the method declaration looks like this:

class ScriptManager
{
  ...

  public int[] loadUsrIDs(object usr_names = null) //by default if usr_names == null then return all user IDs
  {
    ...//reading the database

   return id_users.ToArray();   //from List<int> to int[]
  }

}

Unfortunately, instead of receiving an Int array (int[]), I always get the value: [object Promise] - here's some test code:

var UserID_array = window.external.loadUsrIDs(usr_names);
alert(UserID_array); //alert - only for tests

//The alert function always returns the value: [object Promise]

How can I access the data returned by the C# method in JS?

Best regards,

Marcin

Answer №1

why not give this a shot?

let users = await fetchUsers(usernames);

Answer №2

Patiently await the reply.

After executing your C# function, store the outcomes in a variable (as you have already done).

Next, utilize the feature then(success,failure) to process the data received.

var UserID_array = window.external.loadUsrIDs(usr_names);

UserID_array.then(
    function(result) {
        doSomethingWithYourData(result);            
    }, function (err) { 
        console.log(err); 
    });

This enhances the responsiveness of your page, enabling the user interface to remain interactive while waiting for the data to load.

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

Is there a way to verify in AngularJS whether ng-model contains a string or a numerical value?

In my Angular application, I have written a JavaScript function that checks if the value of a text field is undefined or empty, and it is working properly. $scope.checkNumber = function(user_answer){ if(user_answer == undefined){ return false; } } My ...

Check email validity using jQuery and AJAX before form submission, then continue with AJAX submission

In order to ensure data integrity, the profile creation form on my website includes an email address field that must be in a valid format and not already in use. To validate the format, I utilize a client-side function called isValidEmailAddress. For the e ...

Can you suggest the optimal setup for (javascript SOAP)?

As part of my nightly maintenance process on a LAMP server, I need to retrieve data from a web service using SOAP, which is then applied to a database. While researching various options, I have become overwhelmed by the abundance of information available. ...

jQuery submission not activating

Within a single HTML file, I have two separate forms that operate independently of each other. The issue I am currently encountering is that the $(form).submit((event)=>{code}) function only works on: <form id="mainForm" action='' ...

Enhancing OpenAI API Responses with WebSocket Streaming through Express Middleware Integration

  Currently, I am in the process of developing an Express.js application that requires integration of OpenAI's streaming API responses to be transmitted in real-time to a front-end via WebSockets. Even though I have established communication between ...

AG-Grid: Export the grid with all columns except for two specific ones

My grid has two columns that I need to remain fixed and visible at all times. However, when exporting the grid, I want to exclude these two specific columns. How can I achieve this without affecting the current rendering of the grid? I thought about using ...

Tap here for supplementary HTML

My HTML code looks like this: <a class="link">text</a> <div class="items"></div> (function($) { var link = $('.link'); link.click(function(){ alert('it works!'); }); $('.items').each(fun ...

I am unable to pass a variable through a callback, and I cannot assign a promise to a

Currently, I am facing a challenge with my code where I need to loop through a hard-coded data set to determine the distance from a user-entered location using Google's web API. The issue lies in passing an ID variable down through the code so that I ...

How can I retrieve the Unicode directory name using C#?

I have been attempting to retrieve all directories from my USB drive using the code below: DirectoryInfo di = new DirectoryInfo("H:\\"); DirectoryInfo[] allDir = di.GetDirectories(); This code functions flawlessly for directories with ASCII nam ...

Assign an array value to the input based on the selection made in Javascript

After finding a lot of useful information in previous questions, I am struggling to get the last piece that I need. My PHP code helps me loop through form fields and assign unique names to each field using a variable. One of these fields is for "expense ty ...

Display the data submitted from a PHP form on an HTML webpage

In order to create an online quiz utilizing AJAX, I have developed a registration form where users can input their information. The PHP file will validate the details and return a username if they are correct. My goal now is to redirect users directly to ...

When attaching an event to two functions and then detaching it within a single function

When attaching an event to two functions and then removing it inside one function. Will both functions always be triggered by the event? Or is there a possibility that when the function with the unbind event is executed first, it will unbind both functio ...

Does Platform Toolset v110 have issues with compatibility with .NET 3.5?

In my experience with Visual Studio 2012 Ultimate Update 3, I encountered an issue with a C# project targeting .NET 3.5 that uses a C++/CLI dll also compiled for .NET 3.5. What I observed was that when the C++ dll was compiled with Platform Toolset v110, ...

Loss of Accuracy in HLSL Depth Buffer

I seem to be encountering issues with precision when using the depth buffer on other render targets. My current rendering process is as follows: Draw everything Draw again to depth buffer (using z index as the red channel) Draw lights, passing the depth ...

Error: Attempting to assign value to the 'innerHTML' property of null in a Wordle clone with local storage

While developing a Wordle-inspired game for my website, I decided to utilize Local Storage to store the user's progress. Everything seemed to be working smoothly until an unexpected error occurred: "Uncaught TypeError: Cannot set properties of null (s ...

Customizing material-ui styles within a nested component

I am looking to modify the position of the expandIcon in an ExpansionPanel by changing the right attribute: <ExpansionPanel> <ExpansionPanelSummary expandIcon={<ExpandMoreIcon />}> <Typography className={classes.heading}&g ...

Limiting the usage of a command in Discord.js to one user at a time, rather than all users

I'm in the process of developing a discord.js bot and I need to implement a cooldown for a specific command. After searching several tutorials online, I found that most of them apply the cooldown to all commands (meaning all users have to wait a set ...

Using Nuxtjs/Toast with personalized image emblems

Would it be possible to include an icon in a toast error message, or is there a need to install another module for this functionality? I am currently using vue and attempting to integrate a component as an icon, but so far without success. this.$toast.er ...

Sharing styles between ReactJS and Material-UI - best practices

I am currently facing an issue where I need to share styles across my entire web application. Here is the Problem: I have been using makeStyles in a repetitive manner as shown below: In component_A.js const useStyles = makeStyles({ specific_style: { ...

Conditional rendering is effective for displaying a form item based on certain conditions, but it may not be as effective for

I want a textarea element to appear or disappear based on the selected state of the radio buttons before it. If "no" is chosen, the textarea will be hidden, and if "yes" is chosen, the textarea will become visible. <fieldset class="input-group form-che ...