zoukankan      html  css  js  c++  java
  • 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); }));
  • 相关阅读:
    一些必不可少的Sublime Text 2插件
    sublime text 使用小技巧
    Azure Queue 和 Service Bus Queue的比较
    怎么使用Windows Azure Queue Storage 服务
    配置 SharePoint 2010 使用本机默认 SQL Server 实例 Pan
    将两个字符串中相同的地方str2无重复的输出
    javascript笔记
    C#中怎样使控件随着窗体一起变化大小(拷来学习)
    在pictureBox中画方格矩阵地图,方法比较笨,有好方法望指导
    通过一个小推理写出的程序,结果出乎意料……有哪位知道为什么吗 已解决
  • 原文地址:https://www.cnblogs.com/GengMingYan/p/14337552.html
Copyright © 2011-2022 走看看