使用CefSharp将字符串/ JSON从C#传递给JS

问题描述 投票:0回答:1

我有一个html页面,我想在我的C#应用​​程序(WPF)中托管。因为我需要浏览器基于Chromium而我正在使用cefSharp。

我想将字符串数据从C#传递给JS进行页面初始化。

我发现RegisterJsObject允许我从JS访问一个C#对象,但我似乎无法从中传递任何字符串信息。

我的代码目前看起来像这样:

C#:

mainWindow.browser.RegisterJsObject("csobj", "a string");

JS:

...
console.log(JSON.stringify(window.csobj)); //I get an empty obj {}

我也试图用public string GetJson()方法定义我自己的对象,但是JS不认为它是一个函数,我假设因为它需要一个public void签名。

有没有办法做到这一点?

为了记录,我实际上试图传递一长串单词用于自动完成目的,因此它不仅仅是一个简单的“字符串”。

javascript c# json wpf cefsharp
1个回答
1
投票

您的代码中存在问题:您没有正确注册Js对象,这就是您无法在JS中获取对象的原因。

指南:

RegisterJsObject是注册你的c#对象,然后从JS调用这些方法并将值从JS发送到c#。

如果要将空字符串从c#传递到HTML页面,那么您应该注册JS对象,如下所示:

你的c#类应该如下所示:public class BoundObject {

   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;
        }
    }
}

然后你可以在CefSharp实例中注册这个类,如下所示:

browser = new ChromiumWebBrowser();
browser.RegisterAsyncJsObject("boundAsync", new AsyncBoundObject()); 

注册后,您可以从JS调用该方法,如下所示。

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);
    });
}

您可以看到16和2是正在传递的参数。

希望这可以帮助。

© www.soinside.com 2019 - 2024. All rights reserved.