先将网页弄到iOS项目中:
网页内容如下, 仅供测试:
<html> <head> <meta xmlns="http://www.w3.org/1999/xhtml" http-equiv="Content-Type" content="text/htmlcharset=utf-8" /> <title>这是一个示例html文件</title> <script Type='text/javascript'> function clickme() { alert('点击按钮了!') } </script> </head> <body> <h1>OC与JS互动</h1> <h2>blog.csdn.net/xn4545945</h2> <!-- 自定义协议与OC进行交互 --> <a href="neng://loadUrl/blog.csdn.net">点击一下, 链接调用OC函数</a> <br/> <br/> <a href="http://m.baidu.com">js注入, 到baidu页面上实验</a> </body> </html>
我已经试过这个:string newScript = textBox1.Text
HtmlElement head = browserCtrl.Document.getElementsByTagName_r("head")[0]
HtmlElement scriptEl = browserCtrl.document.create_rElement_x_x("script")
lblStatus.Text = scriptEl.GetType().ToString()
scriptEl.SetAttribute("type", "text/javascript")
head.A(scriptEl)
scriptEl.InnerHtml = "function sayHello() { alert('hello') }"
scriptEl.InnerHtml和scriptEl.InnerText都给出了错误:
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)
有没有一个简单的方法在dom中写入脚本?
dom-文档对象模型
答案:
因为某些原因,Richard的解决方案在结束之前没有工作(insertAdjacentText引发了一个异常,失败了)。不管怎么样,它们似乎是这么工作的:
HtmlElement head = webBrowser1.Document.getElementsByTagName_r("head")[0]
HtmlElement scriptEl = webBrowser1.document.create_rElement_x_x("script")
IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement
element.text = "function sayHello() { alert('hello') }"
head.A(scriptEl)
webBrowser1.Document.InvokeScript("sayHello")