Here is another example where it inserts JavaScript into an Image element which means you will need to click on the image to run the JavaScript.
Add Controls to Form1:
WebBrowser Control
Command1
Command2
Add References to Project
Click on Projects-->References then add
--> OLE Automation
--> Microsoft Internet Controls
Need:
An HTML page that contains an image tag. Note: if page has more than one image the script is added to each image tag unless you specify which image tag to use
Code:Dim DoNotNavigate As Boolean Dim MyURL As String Private Sub Form_Load() DoNotNavigate = False End Sub Private Sub Command1_Click() MyURL = App.Path & "\your_html_page.html" WebBrowser1.Navigate MyURL End Sub Private Sub Command2_Click() Dim scriptNode As Object, headNode As Object Dim oImages As Object, oImage As Object Dim imageNode As Object Set scriptNode = WebBrowser1.Document.createElement("SCRIPT") 'create a new <script> node scriptNode.Type = "text/javascript" 'set type to javascript scriptNode.Text = "function test(){alert('Hello from inserted JS in an Image Tag');}" Set headNode = WebBrowser1.Document.getElementsByTagName("HEAD") 'select <head> node Call headNode(0).appendChild(scriptNode) 'attach <script> node to <head> Do While Not WebBrowser1.ReadyState = READYSTATE_COMPLETE DoEvents Loop Set oImages = WebBrowser1.Document.getElementsByTagName("img") 'select all <img> tags For Each oImage In oImages Set imageNode = WebBrowser1.Document.createElement("A") 'create a new <a> tag imageNode.href = "javascript:test()" imageNode.innerhtml = oImage.outerHTML 'place the <img> tag with all settings imageNode.attachEvent "onclick", WebBrowser1.Document.parentWindow.test() 'attach event to the <a> tag Call oImage.replaceNode(imageNode) 'replace the <img> tag, that is will be <a><img></a> Next End Sub Private Sub WebBrowser1_BeforeNavigate2(ByVal pDisp As Object, URL As Variant, Flags As Variant, TargetFrameName As Variant, PostData As Variant, Headers As Variant, Cancel As Boolean) If URL = MyURL Then Cancel = False Else Cancel = True End If End Sub




Reply With Quote