I have an html page, which I want to host in my C# application (WPF). since I need the browser to be Chromium based I'm using cefSharp.
I want to pass string data from C# to the JS for the page's initialization.
I found RegisterJsObject
which lets me access a C# object from JS, but I can't seem to pass any string information from it.
My code currently looks something like this:
C#:
mainWindow.browser.RegisterJsObject("csobj", "a string");
JS:
...
console.log(JSON.stringify(window.csobj)); //I get an empty obj {}
I've also tried to define my own object with a public string GetJson()
method, but then JS doesn't recognize it as a function, I assume because it expects a public void
signature.
Is there a way to do this?
For the record I'm actually trying to pass a long list of words for auto-complete purposes, so it won't be just a simple 'string'.
Problem in your code: You are not registering Js Object properly and that's why you are not able to get the object in JS.
Guidelines:
RegisterJsObject is to register your c# object and then call those methods from JS and send values from JS to c#.
If you want to pass empty string from c# to your HTML page then you should register JS object like below:
Your c# class should be as shown below:
public class AsyncBoundObject
{
//We expect an exception here, so tell VS to ignore
[DebuggerHidden]
public void Error()
{
throw new Exception("This is an exception coming from C#");
}
//We expect an exception here, so tell VS to ignore
[DebuggerHidden]
public int Div(int divident, int divisor)
{
return divident / divisor;
}
}
Then you can register this class in CefSharp instance as shown below:
browser = new ChromiumWebBrowser();
browser.RegisterAsyncJsObject("boundAsync", new AsyncBoundObject());
After they are registered, you can call the method from JS as shown below.
function asyncDivOk()
{
var call = "Async call (Divide 16 / 2): " + Date();
window.boundAsync.div(16, 2).then(function (res)
{
var end = "Result: " + res + "(" + Date() + ")";
writeAsyncResult(call, end);
});
}
You can see 16 and 2 are the parameters which are being passed.
Hope this helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.