I've been trying to use mshtml to modify a third party web api. Right now I am trying to change the display property on two elements to none so they will be invisible.
I know their id's.
The first one is an img
and the id is zendbox_close
. The second is a div
and the id is zenbox_scrim
.
The html looks like this
<div class="zenbox_header">
<img id="zenbox_close"></img>
</div>
...
<div id="zenbox_scrim...></div>
All I want to do is add in some inline styling so it looks like this
<div class="zenbox_header">
<img id="zenbox_close" style="display:none;"></img>
</div>
...
<div id="zenbox_scrim style="display:none;"...></div>
In my code behind for the WPF WebBrowser
that is opening up the webpage, I have gotten this far:
IHTMLDocument3 doc = (IHTMLDocument3)this._browser.Document;
IHTMLImgElement element = (IHTMLImgElement)doc.getElementById("zenbox_close");
I saw in another post someone was talking about injecting scripts and they said you can use
IHTMLElement scriptEl = doc.CreateElement("script");
I am not sure what the HTML element analog to this would be though. Also I had to use IHTMLDocument3
to use the method getElementById
, but that class doesn't appear to contain anything similar to CreateElement()
.
My question is how can I inject inline styling into a Document
being loaded in my WPF
WebBrowser
?
Yes you can manipulate styles inline.
A good way to do this is to work with the IHTMLStyle or IHTMLCurrentStyle interfaces when working with an IHTMLElement. There are some differences with the values reflected by those two and they are not always synch'd. A better explanation of why that is:
IHTMLStyle vs IHTMLCurrentStyle
Code sample would look like:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
wb.LoadCompleted += wb_LoadCompleted;
wb.Source = new Uri("http://www.google.com");
}
void wb_LoadCompleted(object sender, NavigationEventArgs e)
{
var doc = wb.Document as HTMLDocument;
var collection = doc.getElementsByTagName("input");
foreach (IHTMLElement input in collection)
{
dynamic currentStyle = (input as IHTMLElement2).currentStyle.getAttribute("backgroundColor");
input.style.setAttribute("backgroundColor", "red");
}
}
}