I am trying to load a load a Webpage in C# WebBrowser control (WPF not WinForm).
Along with other content the page has a image rotator that Dynamically creates two divs having same class to utilize the image rotating.
In the LoadComplete event
of the WebBrowser control I am attaching a style sheet to hide the two divs.
The two divs created dynamically onload of the page is follow :
<div class="backgroundImageDivsClass" style="
width: 100%;
height: 100%;
position: fixed;
top: 0px;
left: 0px;
padding: 0px;
margin: 0px;
z-index: -9999;
opacity: 1;
background-image: url("data/767/Course/9214/1000000001_474030834.jpg");
background-position: left top;
background-size: 100% 100%;
background-repeat: no-repeat;
"></div>
<div class="backgroundImageDivsClass"></div>
And the way css is assigned inside LoadComplete event of the webbrowser control is :
mshtml.IHTMLStyleSheet styleSheet = Document.createStyleSheet(string.Empty, 0);
styleSheet.cssText = @".backgroundImageDivsClass{display:none;}";
But this seems not working as its not hiding the divs. Anybody please give me some idea what I am missing.
This is the method I used based on your descriptions and it's working fine.
public MainForm()
{
InitializeComponent();
webBrowser.DocumentCompleted += webBrowser_DocumentCompleted;
var text = @"<html>
<body>
<div class=""backgroundImageDivsClass"">
<span> hello everyone!</span>
</div>
</body>
</html>";
webBrowser.DocumentText = text;
}
void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
var doc = webBrowser.Document.DomDocument as IHTMLDocument2;
var styleSheet = doc.createStyleSheet(string.Empty, 0);
var ruleIndex = styleSheet.addRule(".backgroundImageDivsClass", "display:none", 0);//index can be used to remove the rule
//styleSheet.cssText = @".backgroundImageDivsClass{display:none;}";
}
styleSheet.cssText = @".backgroundImageDivsClass{display:none !important;}";
Is my suggestion. It will force override anything else trying to set the display property. (Like the image rotator control) because any !important tags are applied last by the DOM
To aide further if this doesn't work..
Use the firebug plugin in Firefox, to determine what CSS attributes are applied to your Div dynamically.
You can edit the firebug rendered CSS in real time, until you find a solution that works, then incorporate it in your solution.
This article, augments my suggestions well: http://www.smashingmagazine.com/2010/11/02/the-important-css-declaration-how-and-when-to-use-it/
I believe the problem is that you use the createStyleSheet method on the Document and not on the Document.DomDocument. The answer here can be a useful reference.
Also, as you can read here createStyleSheet is no longer supported. Starting with Internet Explorer 11 you should use document.createElement('style')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With