Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用CefSharp将字符串/JSON从C#传递到JS_Javascript_C#_Json_Wpf_Cefsharp - Fatal编程技术网

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

Javascript 使用CefSharp将字符串/JSON从C#传递到JS,javascript,c#,json,wpf,cefsharp,Javascript,C#,Json,Wpf,Cefsharp,我有一个html页面,我想把它放在我的C#应用程序(WPF)中。 因为我需要浏览器是基于铬的,所以我使用的是cefSharp 我想将字符串数据从C#传递到JS,用于页面的初始化 我找到了RegisterJsObject,它允许我从JS访问C#对象,但我似乎无法从它传递任何字符串信息 我的代码当前看起来像这样: C#: JS: 我还尝试使用公共字符串GetJson()方法定义我自己的对象,但是JS没有将其识别为函数,我假设是因为它需要公共void签名 有办法做到这一点吗 作为记录,我实际上是为了自

我有一个html页面,我想把它放在我的C#应用程序(WPF)中。 因为我需要浏览器是基于铬的,所以我使用的是cefSharp

我想将字符串数据从C#传递到JS,用于页面的初始化

我找到了
RegisterJsObject
,它允许我从JS访问C#对象,但我似乎无法从它传递任何字符串信息

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

C#:

JS:

我还尝试使用
公共字符串GetJson()
方法定义我自己的对象,但是JS没有将其识别为函数,我假设是因为它需要
公共void
签名

有办法做到这一点吗


作为记录,我实际上是为了自动完成而传递一长串单词,所以它不会只是一个简单的“字符串”。

代码中的问题: 您没有正确注册Js对象,因此无法在Js中获取该对象

指南:

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

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

您的c#类应如下所示:

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;
    }
}
browser = new ChromiumWebBrowser();
browser.RegisterAsyncJsObject("boundAsync", new AsyncBoundObject()); 
然后您可以在CefSharp实例中注册该类,如下所示:

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;
    }
}
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是正在传递的参数


希望这有帮助。

谢谢您的回复!但我似乎无法让您的示例工作——对我来说,它抛出了“未捕获的TypeError:window.boundAsync.div(…)。then不是一个函数”。你知道如何解决这个问题吗?nvm-这是一个资本化问题,效果非常好!非常感谢。