CefSharp EvaluateScriptAsync执行js 返回对象、页面元素Node、对象数组

正常情况下,返回单值是没有问题的,但是返回对象,Node这种对象,要想让C#正常接收 js 就得特殊处理一下了:

这里webview就是ChromiumWebBrowser浏览器对象

返回对象

webview.EvaluateScriptAsync("new Object({'name':'zhangsan','age':10})").ContinueWith(new Action<Task<JavascriptResponse>>((respA) => {
    JavascriptResponse resp = respA.Result;
//respObj此时有两个属性: name、age
dynamic respObj = resp.Result; Console.WriteLine(respObj.name + " " + respObj.age); }));

JS返回的对象直接使用 {'name':'zhangsan','age':10} 是不行的,需要用Object对象包起来由于见识太短,不知道什么原因,非常欢迎各位前辈指教,非常感谢!

数组对象

返回数组对象也一样,数组中不能直接使用{xx:xx}形式, 还是需要通过Object返回

webview.EvaluateScriptAsync("[new Object({'name':'zhangsan','age':10})]").ContinueWith(new Action<Task<JavascriptResponse>>((respA) => {
    JavascriptResponse resp = respA.Result;
    List<dynamic> respObj = (List<dynamic>)resp.Result;
    Console.WriteLine(respObj[0].name );
}));

页面对象

页面元素对象有点特殊,直接使用new Object(对象) 是不行的,用到Node元素中哪个属性,需要手动添加:

<a href="http://www.baidu.com" id = "a">A</a>
<a href="http://i.cnblogs.com">B</a>

单个Node对象时,暂时没找到好的转换成Object办法,如果各位前辈有更好的处理办法,请留言!

比如此处用到了A标签的href属性:

//获取A标签的href属性
webview.EvaluateScriptAsync("new Object({href: document.getElementById('a').href})").ContinueWith(new Action<Task<JavascriptResponse>>((respA) => { JavascriptResponse resp = respA.Result; Console.WriteLine(resp.Result.href); }));

多个Node对象时,通过js的Array.from把一个个Node对象拼成了Object对象:

//获取多个A标签href属性
webview.EvaluateScriptAsync("Array.from(document.querySelectorAll('a'), item => new Object({ href: item.href }) );").ContinueWith(new Action<Task<JavascriptResponse>>((respA) => { JavascriptResponse resp = respA.Result; List<dynamic> respObj = (List<dynamic>)resp.Result; Console.WriteLine(respObj[0].href); }));
原文地址:https://www.cnblogs.com/GengMingYan/p/14337552.html