webbrowser对iframe跨域操作问题求解
Private Function getFrames(ByVal WB As WebBrowser) As Object
' 为运行本程序,应在“菜单->工程->部件”中添加“Microsoft Internet Controls”
' 并在“菜单->工程->引用”中添加“Microsoft HTML Object Library”,添加“Edanmo's OLE interfaces & functions v1.4”
Dim pContainer As olelib.IOleContainer
Dim pEnumerator As olelib.IEnumUnknown
Dim pUnk As olelib.IUnknown
Dim pBrowser As SHDocVwCtl.WebBrowser_V1
Set pContainer = WB.object.document
If pContainer.EnumObjects(OLECONTF_EMBEDDINGS, pEnumerator) = 0 Then
Set pContainer = Nothing
Do While pEnumerator.Next(1, pUnk) = 0
On Error Resume Next
Err.Clear
Set pBrowser = pUnk
If Err.Number = 0 Then
If InStr(pBrowser.LocationURL, "目标网址") Then
Set getFrames = pBrowser
Exit Function
End If
End If
Loop
Set pEnumerator = Nothing
End If
End Function
Private Sub Command1_Click()
MsgBox getFrames(wb1).LocationURL
MsgBox getFrames(wb1).document.getElementById("a1").innerHTML
End Sub
如上代码,最后command1在点击时能成功获得目标iframe的URL,但后面句(MsgBox getFrames(wb1).document.getElementById("a1").innerHTML)获取目标元素时发生错误,错误代码438,对象不支持该属性或方法,求解问题原因
[解决办法]
Dim xxx As Object
Private Sub WebBrowser1_DocumentComplete(ByVal pDisp As Object, URL As Variant)
If URL = "目标frame网址" Then Set xxx = pDisp
End Sub
xxx此时相当于那个frame的document对象了,可以自由操作。
msgbox xxx.document.body.innerHTML