如何在WebBrowser控件中注入CSS

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (99)
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        webBrowser1.Navigate("https://www.aparat.com/aleffamily/live2");
        webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted;

    }

    private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {

        HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];
        HtmlElement styleEl = webBrowser1.Document.CreateElement("style");
        IHTMLStyleElement element = (IHTMLStyleElement)styleEl.DomElement;
        IHTMLStyleSheetElement styleSheet = element.styleSheet;
        styleSheet.cssText = @"body {background-color:transparent !important; margin: 0px auto; overflow: hidden; }.live__content{display:none;}.chat__footer{display:none;}.chat__header{display:none}#header{display:none}.in-chat-avatar{display:none}.message__username{font-style:italic;font-weight: 800!important;color:ff8f0f !important}.message__text{font-style:italic;font-weight: 400!important;color:ff8f0f !important}.chat__content{ background-color:transparent  !important}.chat{ background-color:transparent  !important}";
        head.AppendChild(styleEl);

    }


}

}

这段代码对我没有用,我收到了这个错误

错误1找不到类型或命名空间名称'IHTMLStyleSheetElement'(您是否缺少using指令或程序集引用?)C:\ Users \ aleffamily \ documents \ visual studio 2010 \ Projects \ WindowsFormsApplication1 \ WindowsFormsApplication1 \ Form1.cs 30 13 WindowsFormsApplication1

提问于
用户回答回答于

什么是你想用引用IHTMLStyleElementIHTMLStyleSheetElement?它不是.NET框架中的任何地方。

只需修改您的代码编写通用的内容HtmlElement类型,而不是通过编写的内容.InnerText.InnerHtml你的样式表

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        webBrowser1.Navigate("https://www.aparat.com/aleffamily/live2");
        webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted;
    }

    private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {

        HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];
        HtmlElement styleEl = webBrowser1.Document.CreateElement("style");
        styleEl.InnerHtml = @"body {background-color:transparent !important; margin: 0px auto; overflow: hidden; }.live__content{display:none;}.chat__footer{display:none;}.chat__header{display:none}#header{display:none}.in-chat-avatar{display:none}.message__username{font-style:italic;font-weight: 800!important;color:ff8f0f !important}.message__text{font-style:italic;font-weight: 400!important;color:ff8f0f !important}.chat__content{ background-color:transparent  !important}.chat{ background-color:transparent  !important}";
        head.AppendChild(styleEl);

    }
}

扫码关注云+社区

领取腾讯云代金券