VBA - 将创建的 HTML 元素附加到 HEAD 元素时出现问题
VBA - Issue appending a created HTML element to a HEAD element
我正在尝试在 UserForm Webbrowser 控件和表单本身之间实现 javascript 'bridge'。我觉得我现在快到了,见下文。但我似乎无法将创建的脚本附加到加载到网络浏览器中的文档的头部。错误是 "Object required" 行 "head.appendChild (scriptEl)"。我使用 msgbox 来显示 head.innerHTML,其中显示了所有 HTML,并且 scriptEl.innerHTML 具有完整的脚本元素,所以不确定为什么会发生该错误。
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
我建议使用以下代码:
' 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
我正在尝试在 UserForm Webbrowser 控件和表单本身之间实现 javascript 'bridge'。我觉得我现在快到了,见下文。但我似乎无法将创建的脚本附加到加载到网络浏览器中的文档的头部。错误是 "Object required" 行 "head.appendChild (scriptEl)"。我使用 msgbox 来显示 head.innerHTML,其中显示了所有 HTML,并且 scriptEl.innerHTML 具有完整的脚本元素,所以不确定为什么会发生该错误。
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
我建议使用以下代码:
' 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