您的位置:首页 > Web前端 > JavaScript

终于用 C# 把 WebBrowser 页面中的 js 变量取出来了!

2013-10-27 17:31 681 查看
通过 WebBrowser 可以在页面中执行 js 函数,与取得 js 变量值还是有一定距离,考虑到既然可以获取页面元素,为什么不通过页面元素曲线救国呢?马上行动。

1 用万能的 eval 自定义一个函数,用来完成需要的操作

2 再用 eval 调用定义的函数传入特定的参数:

public static string htmlid = Guid.NewGuid().ToString();
private string GetJsVar(WebBrowser webBrowser1, string varname)
{
if (webBrowser1.Document == null)
return "No document";

webBrowser1.Document.InvokeScript("eval", new[]{ @"
CreateHiddenInputForReturn = function(id, val) {
var elm = document.getElementById(id);
if(elm == null) {
elm = document.createElement('INPUT');
elm.id = id;
elm.type=""HIDDEN"";
document.body.insertBefore(elm);
}
elm.value = eval('typeof('+val.split(/[\[\.]/)[0]+')')=='undefined' ? id : eval(val);
}
"});
webBrowser1.Document.InvokeScript("CreateHiddenInputForReturn", new[] { htmlid, varname });
HtmlElement obj = webBrowser1.Document.GetElementById(htmlid);
if (obj != null)
{
string val = obj.GetAttribute("value");
if (val == htmlid)
return "no js var";
return val;
}
return "null";
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: