如何在WebBrowser控件中注入Javascript ?
16lz
2021-01-22
I've tried this:
我已经试过这个:
string newScript = textBox1.Text;
HtmlElement head = browserCtrl.Document.GetElementsByTagName("head")[0];
HtmlElement scriptEl = browserCtrl.Document.CreateElement("script");
lblStatus.Text = scriptEl.GetType().ToString();
scriptEl.SetAttribute("type", "text/javascript");
head.AppendChild(scriptEl);
scriptEl.InnerHtml = "function sayHello() { alert('hello') }";
scriptEl.InnerHtml and scriptEl.InnerText both give errors:
scriptEl。InnerHtml,scriptEl。InnerText都给实现错误:
System.NotSupportedException: Property is not supported on this type of HtmlElement.
at System.Windows.Forms.HtmlElement.set_InnerHtml(String value)
at SForceApp.Form1.button1_Click(Object sender, EventArgs e) in d:\jsight\installs\SForceApp\SForceApp\Form1.cs:line 31
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
Is there an easy way to inject a script into the dom?
是否有一种简单的方法将脚本注入dom?
14 个解决方案
#1
89
For some reason Richard's solution didn't work on my end (insertAdjacentText failed with an exception). This however seems to work:
由于某些原因,Richard的解决方案并没有在我的结束(insert邻接文本以一个异常失败)结束。然而,这似乎起了作用:
HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];
HtmlElement scriptEl = webBrowser1.Document.CreateElement("script");
IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;
element.text = "function sayHello() { alert('hello') }";
head.AppendChild(scriptEl);
webBrowser1.Document.InvokeScript("sayHello");
This answer explains how to get the IHTMLScriptElement
interface into your project.
这个答案解释了如何将IHTMLScriptElement接口引入到您的项目中。
更多相关文章
- Javascript等待函数的结束,包括node.js的异步MYSQL查询?
- 如何在详细信息标记的结束事件上添加CSS转换?
- 等待执行所有ajax回调的最佳解决方案
- 希望日期开始结束在一个数组中的while循环中为一个房间ID
- 【问题解决方案】ImportError: No module named 'pygal'
- Python 黏包及黏包解决方案
- 在Django,我的request.session没有结束......有谁知道为什么?
- 脚本结束后如何运行进程并退出?
- 无法安装ndg-httpsclient或者我的解决方案错误