如何注入CSS在WebBrowser控件? [英] How to inject CSS in WebBrowser control?

查看:1612
本文介绍了如何注入CSS在WebBrowser控件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

按我所知,没有办法的javascript到DOM注入。下面是示例code表示注入的JavaScript与 web浏览器控制:

As per my knowledge,there is a way to inject javascript into the DOM. Below is the sample code that injects javascript with the webbrowser control:

HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];
HtmlElement scriptEl = webBrowser1.Document.CreateElement("script");
IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;
element.text = "function sayHello() { alert('hello') }";
head.AppendChild(scriptEl);
webBrowser1.Document.InvokeScript("sayHello");

有没有更简单的方式来注入的CSS到DOM?

Is there an easier way to inject css into the DOM?

推荐答案

我没有尝试这个自己,但由于CSS样式规则可以使用包含在文档中的<风格> 标签中:

I didn't try this myself but since CSS style rules can be included in a document using the <style> tag as in:

<html>
<head>
<style type="text/css">
    h1 {color:red}
    p {color:blue}
</style>
</head>

您可以尝试,并提供:

HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];
HtmlElement styleEl = webBrowser1.Document.CreateElement("style");
IHTMLStyleElement element = (IHTMLStyleElement)styleEl.DomElement;
IHTMLStyleSheetElement styleSheet = element.styleSheet;
styleSheet.cssText = @"h1 { color: red }";
head.AppendChild(styleEl);

一展身手。您在这里可以找到的IHTMLStyleElement 更多信息。

a go. You can find more info on the IHTMLStyleElement here.

看来答案是非常非常简单的,比我原来想象:

It seems the answer is much much simpler than I originally thought:

  IHTMLDocument2 doc = (webBrowser1.Document.DomDocument) as HTMLDocument2;
  // The first parameter is the url, the second is the index of the added style sheet.
  IHTMLStyleSheet ss = doc.createStyleSheet("", 0);

  // Now that you have the style sheet you have a few options:
  // 1. You can just set the content as text.
  ss.cssText = @"h1 { color: blue; }";
  // 2. You can add/remove style rules.
  int index = ss.addRule("h1", "color: red;");
  ss.removeRule(index);
  // You can even walk over the rules using "ss.rules" and modify them.

我写了一个小的测试项目,以验证其工作原理。我来到这个最终的结果通过MSDN上做一个搜索IHTMLStyleSheet,在这我偶然横跨<一href="http://social.msdn.microsoft.com/Forums/en-US/ieextensiondevelopment/thread/49dc2c07-ea26-4734-aa2c-99a109ccb46a">this页面,<一个href="http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/f18898b2-9313-4327-a4d9-6104831bfd69/">this页面和<一href="http://social.msdn.microsoft.com/forums/en-US/iewebdevelopment/thread/33fd33f7-e857-4f6f-978e-fd486eba7174/">this 之一。

这篇关于如何注入CSS在WebBrowser控件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆