Accessing the content of an HTMLViewer in JavaScript

I have been asked to provide a way to access the content of an HTMLViewer in JavaScript. Contrary to other controls, the HTMLViewer uses an iFrame, which makes the process a bit more complex. I thought I post the way here, as it can be of interest to the community.

Here is an example.

In the HTMLViewer :

Sub Open() me.LoadPage("<html><head></head><body><div id='mydiv'>div contents</div></body></html>") End Sub

Here is what is needed to modify the mydiv content in JavaScript:

dim theelement as string = "mydiv" dim newtext as string = "this is the new text" dim thejavascript as string thejavascript = thejavascript + "var HTMLViever= document.getElementById('"+HTMLViewer1.ControlID+"');" thejavascript = thejavascript + "var VieweriFrame=HTMLViever.getElementsByTagName('iframe');" thejavascript = thejavascript + "var viewerDom=VieweriFrame[0].contentDocument ;" thejavascript = thejavascript + "viewerDom.getElementById('"+theelement+"').innerHTML = '"+newtext+"';" HTMLViewer1.ExecuteJavaScript(thejavascript)

First line gets the HTMLViewer in the dom
Second line gets the iFrame inside the Div
Third line gets a reference to the document inside the iFrame.
Then your code can be used.

Note that you will not be able to do that on pages loaded from another domain, as it becomes off limit for security reasons.