1

目前我正在用 C# 为 Internet Explorer 编写一个插件。这是我第一次尝试使用 .net 和 Internet Explorer 插件。与 Java 相比,C# 具有很好的语言特性。

但是,我被困住了。我找不到一种简单/或一般的方式来修改 DOM。

我的插件应该具有向站点显示 Html 标头的功能。

在Javascript中我会做这样的事情:

var a = document.createElement('a');
var text_node = document.createTextNode(text);
var href = document.createAttribute("href");
href.nodeValue = url;
a.setAttributeNode(href);
a.appendChild(text_node); 
var my_dom = document.createElement('div');
my_dom.appendChild(a);
my_dom.style.background = '#36b';;
document.body.insertBefore(my_dom, document.body.firstChild);

我使用 www.codeproject.com/KB/cs/Attach_BHO_with_C_.aspx 上的教程来熟悉 BHO 和 Internet Explorer 开发。然而,在这个插件中,包 mshtml 用于访问 dom。我找不到通过 api 向 dom 添加新元素的好方法。在网上搜索时,我发现 System.Windows.Forms.HtmlDocument 有一个 appendChild 函数。但是,当我将程序转换为 System.Windows.Forms 时,它根本不起作用。

有人可以告诉我如何修改(在正文的开头插入一个html元素)dom吗?

这是我的程序框架的链接https://gist.github.com/fd4459dc65acd7d167b6 首先,它足以向我展示如何在 OnDocumentComplete 函数的正文开头添加一个方法。

谢谢

4

2 回答 2

1

经过搜索和搜索,我找到了解决方案。我没有找到通过 mshtml 修改 DOM 的方法,而是通过 javascript。Javascript可以通过注入

document.parentWindow.execScript("alert('hello world')");

我可以重用我现有的 javascripts 来解决这个问题。

于 2010-12-01T19:39:32.423 回答
1

如果你有不止一行 Javascript 代码,你可以有多行 execScript。例子:

document.parentWindow.execScript("var trends_dom = document.createElement('div')");
document.parentWindow.execScript("var title_dom = document.createElement('strong')");
document.parentWindow.execScript("var text_dom = document.createTextNode('test')");
document.parentWindow.execScript("title_dom.innerText = 'This text is placed over a web page'");
document.parentWindow.execScript("trends_dom.appendChild(title_dom)");
document.parentWindow.execScript("trends_dom.appendChild(text_dom)");
document.parentWindow.execScript("trends_dom.style.background = '#36b'");
document.parentWindow.execScript("trends_dom.style.color = '#fff'");
document.parentWindow.execScript("trends_dom.style.padding = '10px'");
document.parentWindow.execScript("trends_dom.style.position = 'fixed'");
document.parentWindow.execScript("trends_dom.style.zIndex = '123456'");
document.parentWindow.execScript("trends_dom.style.top = '20px'");
document.parentWindow.execScript("trends_dom.style.font = '14px Arial'");
//document.body.appendChild(trends_dom);
document.parentWindow.execScript("document.body.insertBefore(trends_dom, document.body.firstChild)");
于 2011-05-02T17:04:11.757 回答