Search code examples
javascriptexcelvbauserform

VBA - Issue appending a created HTML element to a HEAD element


I am trying to achieve a javascript 'bridge' between a UserForm Webbrowser control and the form itself. I feel like I am almost there now, see below. But I cannot seem to append the created script to the Head of the document loaded into the webbrowser. The error is "Object required" at line "head.appendChild (scriptEl)". I used msgbox to display head.innerHTML which shows all the HTML, and also scriptEl.innerHTML has the fully formed script element, so not sure why that error is happening.

Private Sub CommandButton2_Click()

Dim head As HTMLGenericElement
Dim scriptEl As HTMLScriptElement
Dim element As HTMLScriptElement



Set head = WebBrowser1.Document.GetElementsByTagName("head")(0)
Set scriptEl = WebBrowser1.Document.createElement("script")

    scriptEl.Text = "function sayHello() { alert('hello') }"
    head.appendChild (scriptEl)
    WebBrowser1.Document.InvokeScript ("sayHello")

End Sub

Solution

  • I would suggest the following code:

    ' Add references
    ' Microsoft Internet Controls
    ' Microsoft HTML Object Library
    
    Private Sub UserForm_Initialize()
    
        With WebBrowser1
            .Navigate "about:blank"
            Do Until .ReadyState = READYSTATE_COMPLETE And Not .Busy: DoEvents: Loop
            .Document.parentWindow.execScript "function sayHello() { alert('hello') }"
        End With
    
    End Sub
    
    Private Sub CommandButton2_Click()
    
        WebBrowser1.Document.parentWindow.execScript "sayHello();"
    
    End Sub