Mars base one Username: Jim Davis Password: yCrm33
Posts
1,284
Inject a Javascript code to a HTM document by using WebBrowser Control
vb Code:
Private Sub Form_Load()
Me.Show
DoEvents
WebBrowser1.Navigate "http://www.vbforums.com"
Do While Not WebBrowser1.ReadyState = READYSTATE_COMPLETE
DoEvents
Loop
Dim scriptNode As Object, headNode As Object
Set scriptNode = WebBrowser1.Document.createElement("SCRIPT") 'create a new <script> node
scriptNode.Type = "text/javascript" 'set type to javascript
scriptNode.Text = "function showMe(e) { alert(e.srcElement.src); e.srcElement.parentNode.outerHTML = e.srcElement.outerHTML; }" 'inject javascript code. After the src tag shown up, it will revert the changes on that image, so you get back the normal behavior.
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
Dim oImages As Object, oImage As Object. imageNode As Object
Set oImages = WebBrowser1.Document.getElementsByTagName("img") 'select all <img> tags
'Select an image, temporarily neutralizes any <a> tag around the image, then attach an onclick event to it.
For Each oImage In oImages
Set imageNode = WebBrowser1.Document.createElement("A") 'create a new <a> tag
imageNode.href = "javascript:void(0)" 'the href will be a .. nothing :)
imageNode.attachEvent "onclick", WebBrowser1.Document.parentWindow.showMe() 'attach event to the <a> tag
imageNode.innerHtml = oImage.outerHTML 'place the <img> tag with all settings
Call oImage.replaceNode(imageNode) 'replace the <img> tag, that is will be <a><img></a>
Next
End Sub
The code will inject a simple javascript to the downloaded htm document, also attach event to each <img> (see: *1) tags, so it will pop up a messagebox, containing the src= property of any image you are clicked on.
Edit:
- The onclick event will be attached to the <a> tag that is a temporary tag. (*1)
- If you click on an image, the src property of the image will be displayed, then it reverts the changes.
Edit2:
Code attached, that demonstrate an intelligent (vb6) way to inject the js, then clean up all changes, to revert the original. You can inject/remove the extra code any time to any pages you are browsing.
Last edited by Jim Davis; Feb 21st, 2009 at 04:29 PM.