Csharp Webbrowser—解决乱码,解决js注入html无法运行
2016-10-01
- 1、webbrowser自动在百度搜索框输出文字时乱码,同时以汉字直接在控制台输出也是乱码
- 2、注入html中的js脚本无法运行,alert(\”hello\”)同样无法运行
我的解决方法
- 1、将有中文字符的*.cs文件通过记事本另存为,更改编码为utf-8
- 2、见代码
代码块
//加入脚本到当前iframe的head处,
//webbrowser ex;
HtmlWindow hwc = ex.Document.Window.Frames["mainframe"];
if (hwc != null)
{
HtmlElement head = hwc.Document.GetElementsByTagName("head")[0];
HtmlElement scriptEl = hwc.Document.CreateElement("script");
IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;
element.text = "function hello() { alert(\"hello\") }";
head.AppendChild(scriptEl);
hwc.Document.InvokeScript("hello");
}
//加入脚本当html的head处
//webbrowser hwc;
HtmlElement head = hwc.Document.GetElementsByTagName("head")[0];
HtmlElement scriptEl = hwc.Document.CreateElement("script");
IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;
element.text = "function hello() { alert(\"hello\") }";
head.AppendChild(scriptEl);
hwc.Document.InvokeScript("hello");
体会:初次解决困扰好几天的两大难题,难掩喜悦,遂于诸君共享。前事之不忘,后事之师。