我正在尝试将我为Google Chrome编写的content script转换为IE插件,主要是使用this answer中的代码。
我需要注入一个样式表,我找到了way to do it using Javascript。我以为我可以用C#做同样的事情。这是我的代码:
[ComVisible(true)]
[Guid(/* replaced */)]
[ClassInterface(ClassInterfaceType.None)]
public class SimpleBHO: IObjectWithSite
{
private WebBrowser webBrowser;
void webBrowser_DocumentComplete(object pDisp, ref object URL)
{
var document2 = webBrowser.Document as IHTMLDocument2;
var document3 = webBrowser.Document as IHTMLDocument3;
// trying to add a '<style>' element to the header. this does not work.
var style = document2.createElement("style");
style.innerHTML = ".foo { background-color: red; }";// this line is the culprit!
style.setAttribute("type", "text/css");
var headCollection = document3.getElementsByTagName("head");
var head = headCollection.item(0, 0) as IHTMLDOMNode;
var result = head.appendChild(style as IHTMLDOMNode);
// trying to repace an element in the body. this part works if
// adding style succeeds.
var journalCollection = document3.getElementsByName("elem_id");
var journal = journalCollection.item(0, 0) as IHTMLElement;
journal.innerHTML = "<div class=\"foo\">Replaced!</div>";
// trying to execute some JavaScript. this part works as well if
// adding style succeeds.
document2.parentWindow.execScript("alert('Hi!')");
}
int IObjectWithSite.SetSite(object site)
{
if (site != null)
{
webBrowser = (WebBrowser)site;
webBrowser.DocumentComplete += new DWebBrowserEvents2_DocumentCompleteEventHandler(webBrowser_DocumentComplete);
}
else
{
webBrowser.DocumentComplete -= new DWebBrowserEvents2_DocumentCompleteEventHandler(webBrowser_DocumentComplete);
webBrowser = null;
}
return 0;
}
/* some code (e.g.: IObjectWithSite.SetSite) omitted to improve clarity */
}
如果我只是注释掉以下行...
style.innerHTML = ".foo { background-color: red; }";
...代码的其余部分完美执行(替换元素#elem_id
并执行我注入的JavaScript)。
尝试注入样式表时,我做错了什么?这甚至可能吗?
编辑:我发现我试图注入CSS的网站请求文档模式5,当兼容性视图禁用时,我的代码完美运行。但是,即使兼容性视图启用,我该如何使其工作?
答案 0 :(得分:0)
经过大量的实验,我发现只有使用JavaScript注入样式表才能使用document2.parentWindow.execScript()
(document2
执行IHTMLDocument2
)的方式注入样式表。
我使用了以下JavaScript:
var style = document.createElement('style');
document.getElementsByTagName('head')[0].appendChild(style);
var sheet = style.styleSheet || style.sheet;
if (sheet.insertRule) {
sheet.insertRule('.foo { background-color: red; }', 0);
} else if (sheet.addRule) {
sheet.addRule('.foo', 'background-color: red;', 0);
}
上述JavaScript在以下版本中执行:
// This code is written inside a BHO written in C#
document2.parentWindow.execScript(@"
/* Here, we have the same JavaScript mentioned above */
var style = docu....
...
}");
document2.parentWindow.execScript("alert('Hi!')");