Reputation: 497
Using VB.NET 2010 (Winforms) and targeting .NET 2.0 framework.
On form load, I have a webbrowser control that navigates to a specific URL. Once that URL has been fully loaded by the browser, I click button1 which I want to do the following --> dynamically create a new CSS class named "dashedBorder" in the 'head' section of the loaded webpage DOM. Here's button1's click event code...
Dim Document As HtmlDocument = WebBrowser1.Document
Dim Head As HtmlElement = Document.GetElementsByTagName("head")(0)
Dim SelectedStyle As HtmlElement = Document.CreateElement("style")
SelectedStyle.InnerText = ".dashedBorder {border: 2px dashed yellow !important;}"
Head.AppendChild(SelectedStyle)
When I run the above code, I get a VB error message stating "Property is not supported on this type of HtmlElement".
Any ideas how to create the new CSS class in this scenario? FYI, I do not want to assign that CSS to any particular element at this point -- I simply wish to create the class (in the DOM) so that I can toggle that class on and off with jQuery later on in the code.
Upvotes: 0
Views: 2432
Reputation: 61744
This question is a good starting point, but actually it's more simple to make it work in WebBrowser
control for all IE versions, than described there:
SelectedStyle
style object (NativeSelectedStyle = SelectedStyle.DomElement
);NativeSelectedStyle.type
needs to be set to "text/css"
;NativeSelectedStyle.styleSheet
becomes available, otherwise it is Nothing
;NativeSelectedStyle.styleSheet.cssText
to your style sheet content.Complete example:
Public Class Form1
Private Sub WebBrowser1_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
Dim Document As HtmlDocument = WebBrowser1.Document
Dim Head As HtmlElement = Document.GetElementsByTagName("head")(0)
Dim SelectedStyle As HtmlElement = Document.CreateElement("style")
Dim NativeSelectedStyle = SelectedStyle.DomElement
NativeSelectedStyle.type = "text/css"
' NativeSelectedStyle.innerHTML = ".dashedBorder { ... }" throws an error
NativeSelectedStyle.styleSheet.cssText = ".dashedBorder {border: 2px dashed yellow !important;}"
Head.AppendChild(SelectedStyle)
MessageBox.Show(SelectedStyle.OuterHtml)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
WebBrowser1.Navigate("about:blank")
End Sub
End Class
[EDITED] Now I've found that I essentially copied this answer, so the credit should go to @paracycle. Making this one a wiki.
Upvotes: 1