CefSharp 中文帮助文档(五):Js/JavaScript处理

.Net技术 码拜 7年前 (2017-04-12) 16904次浏览 1个评论

通过在CefSharp中执行Js 脚本,可以对网页对象进行控制

5.1 基本的同(异)步js操作,针对MainFrame

browser.GetBrowser().MainFrame.ExecuteJavaScriptAsync("document.getElementById('testid').click();");  
browser.GetBrowser().MainFrame.ExecuteJavaScriptAsync("document.getElementById('testid2').value='123'");

5.2 其他Frame操作

//要执行的脚本
string script = "if(document.getElementById('img_out_10000')){ document.getElementById('img_out_10000').click(); }";  
//获取多个Frame
var list = browser.GetBrowser().GetFrameNames();  
if (list.Count > 1)  
{  
    browser.GetBrowser().GetFrame(list[1]).ExecuteJavaScriptAsync(script);  
}

5.3 在js中回调C#类的方法/如何给js暴露一个C#类

像这样即可实现js和c#的交互:

//定义C#类
public class BoundObject  
{  
    public string MyProperty { get; set; }  
    public void MyMethod()  
    {  
        // Do something really cool here.  
    }  
}  
// ...  
// After your ChromiumWebBrowser has been created  
//将BoundObject类注册为Js对象,名称为bound
browser.RegisterJsObject("bound", new BoundObject());  

//完成以上C#中的设置后,就可以在Js中调用C#方法了
//In the actual JS code, you would use the object like this:  
bound.myProperty; // use this syntax to access the property  
bound.myMethod(); // use this to call the method.

 


CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明CefSharp 中文帮助文档(五):Js/JavaScript处理
喜欢 (2)
[1034331897@qq.com]
分享 (0)

文章评论已关闭!

(1)个小伙伴在吐槽
  1. C#中定义的方法须为小写 :smile:
    ZSQDH2018-11-08 17:34 回复