我无法使用CefSharp从WinForms的c#中获得一些数组

时间:2019-06-22 19:57:06

标签: javascript c# cefsharp

我有Chromium的Win Forms应用程序。我的目标是获取在C#领域生成的字符串变量(json),以便与javascript函数一起使用。我在javascript-land无法获得它。

我在JSObj.cs创建了mefod getJSON()-它生成了json。我从方法中看到了字符串。我在Form1.cs(这里有Chromium)上注册了Oblect JSObj。我用按钮从html调用了JSObj.getJSON(),但是我没有在javascript代码中使用json!

<button class="btn btn-info" id="btn3">Test Winform Interaction</button>
$("#btn3").on('click', function () {
            alert(jSObject.getJSON()[0]);
        });
public string getJSON()
        {
            DispHandler hand = new DispHandler(delegate
            {
                string directoryPath = @"C:\";
                List<SObject> sendObjects = new List<SObject>();
                DirectoryInfo directoryInfo = new DirectoryInfo(directoryPath);
                FileInfo[] filesArray = directoryInfo.GetFiles();
                foreach (var el in filesArray)
                {
                    sendObjects.Add(new SObject(el.Name, directoryPath));
                }
                string json = JsonConvert.SerializeObject(sendObjects);
                return json;
            });
            IAsyncResult resultObj = hand.BeginInvoke(null, null);
            var res = hand.EndInvoke(resultObj);
            return res;
        }
public Form1()
        {
            InitializeComponent();
            InitializeChromium();            
            _browser.RegisterAsyncJsObject("jSObject", new JSObj());
        }

没有错误。我希望在javascript-land中获得json数据。

1 个答案:

答案 0 :(得分:1)

C#与CEF之间的通信是异步的,jSObject.getJSON()返回一个Promise作为结果,而不是结果本身。尝试以下JS代码:

$("#btn3").on('click', function () {
    jSObject.getJSON().then(function (r) { alert(r[0]); });
});