通过在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.