Webbrowser控件注入JS和CSS

时间:2013-10-10 10:26:51

标签: c# javascript wpf winforms webbrowser-control

我的应用程序中有Webrowser控件,我想将cssjavascript注入其中。 在我的winform应用中,我已经完成了:

string jqueryCode = System.IO.File.ReadAllText(@"JQuery.js");

HtmlElement head2 = browser.Document.GetElementsByTagName("head")[0];
HtmlElement scriptEl2 = browser.Document.CreateElement("script");
IHTMLScriptElement element2 = (IHTMLScriptElement)scriptEl2.DomElement; 
element2.text = jqueryCode;
head2.AppendChild(scriptEl2);


string css = System.IO.File.ReadAllText(@"local_page.css");

HTMLDocument CurrentDocument = (HTMLDocument)browser.Document.DomDocument;
IHTMLStyleSheet styleSheet = CurrentDocument.createStyleSheet("", 0);
styleSheet.cssText = css;

string javaScriptCode = System.IO.File.ReadAllText(@"Script.js");

HtmlElement head = browser.Document.GetElementsByTagName("head")[0];
HtmlElement scriptEl = browser.Document.CreateElement("script");
IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;
element.text = javaScriptCode;
head.AppendChild(scriptEl);

browser.InvokeScript("myfunction");

它完美无缺。现在,我在WPF应用程序中执行此操作:

string jqueryCode = System.IO.File.ReadAllText(@"JQuery.js");

var doc = (HTMLDocument)browser.Document;
var head = doc.getElementsByTagName("head").Cast<HTMLHeadElement>().First();
var script = (IHTMLScriptElement)doc.createElement("script");
script.text = jqueryCode;
head.appendChild((IHTMLDOMNode)script);


string css = System.IO.File.ReadAllText(@"local_page.css");

var doc2 = (HTMLDocument)browser.Document;
var head2 = doc2.getElementsByTagName("head").Cast<HTMLHeadElement>().First();
var script2 = (IHTMLStyleSheet)doc2.createStyleSheet("");
script2.cssText = css;

string javaScriptCode = System.IO.File.ReadAllText(@"Script.js");

var doc3 = (HTMLDocument)browser.Document;
var head3 = doc3.getElementsByTagName("head").Cast<HTMLHeadElement>().First();
var script3 = (IHTMLScriptElement)doc3.createElement("script");
script3.text = javaScriptCode;
head3.appendChild((IHTMLDOMNode)script3);

browser.InvokeScript("myfunction");

它会产生问题。知道问题是什么吗?

0 个答案:

没有答案