主にこの回答のコードを使用して、Google Chrome 用に作成したコンテンツ スクリプトを IE アドオンに変換しようとしています。
スタイルシートを挿入する必要がありましたが、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 を要求していることがわかりました。互換表示が無効になっていると、私のコードは完全に機能します。しかし、互換表示が有効になっている場合でも動作させるにはどうすればよいですか?