Csharp Webbrowser---解决乱码,解决js注入html无法运行

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");

体会:初次解决困扰好几天的两大难题,难掩喜悦,遂于诸君共享。前事之不忘,后事之师


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值