VBA:从InternetExplorer对象访问LocalStorage

时间:2014-04-22 17:54:04

标签: javascript vba local-storage

是否有更简单/直接的方法从Internet Explorer对象访问localstorage变量,除了执行JS以在DOM上创建值?

我有自己的自定义解决方案利用临时文本字段,但我想知道MS是否提供直接功能。

Function retrieveLocalStorageValue(sURL As String, sLocalStorageVarName As String) As String

     On Error GoTo ErrHandler1:

        Dim javascriptString As String
        Set oBrowser = New InternetExplorer
        oBrowser.Silent = True
        oBrowser.navigate sURL
        oBrowser.Visible = True

        Do
        ' Wait till the Browser is loaded
        Loop Until oBrowser.readyState = READYSTATE_COMPLETE

    On Error GoTo ErrHandlerJscript:

        javastringUrl = "document.body.innerHTML += '<input id=\""test1234\"" type=\""text\"" value=\""'+ localStorage.getItem('" & sLocalStorageVarName & "') +'\""\>';"
        'Execute javascript to create hidden field - Use double quotes in VBA to escape

        'Wait in case it is needed
        Application.Wait DateAdd("s", 1, Now)

        oBrowser.document.parentWindow.eval javastringUrl
        retrieveLocalStorageValue = oBrowser.document.getElementById("test1234").getAttribute("value")

    Exit Function

ErrHandler1:
    MsgBox ("Error, debugging required")
    retrieveLocalStorageValue = "error"

ErrHandlerJscript:
    MsgBox ("Error with javascript execution, debugging required")
    retrieveLocalStorageValue = "error"
End Function


Sub test()
    Dim test As String
    test = retrieveLocalStorageValue("http://127.0.0.1/stackexchange/localStorageVBA.html", "testObject")
    MsgBox test
End Sub

参考:http://maythesource.com/2014/04/22/vba-read-localstorage-variable-from-internet-explorer-object-using-temporary-textfield/

1 个答案:

答案 0 :(得分:1)

不,不是真的。是的,您可以设置对Microsoft Internet Explorer的引用和对Microsoft HTML Object Library的引用。这将允许您直接访问DOM对象模型,并且intellisense将起作用。但是,如果您实际尝试访问该属性,则会抛出错误。 (如下所示:)

Option Explicit

Sub Example()
    ThisFails "http://www.w3schools.com/html/tryit.asp?filename=tryhtml5_webstorage_local", "lastname"
End Sub

Function ThisFails(ByVal sURL As String, ByVal sLocalStorageVarName As String) As String
    Dim oBrowser As SHDocVw.InternetExplorer
    Dim hDoc As MSHTML.HTMLDocument
    Dim hWin As MSHTML.HTMLWindow2
    Set oBrowser = New SHDocVw.InternetExplorer
    oBrowser.Silent = True
    oBrowser.Navigate sURL
    oBrowser.Visible = True

    Do
        ' Wait till the Browser is loaded
    Loop Until oBrowser.ReadyState = READYSTATE_COMPLETE
    Do
        Set hDoc = oBrowser.Document
        'Trust me on these loops
    Loop While hDoc Is Nothing
    Do
        Set hWin = hDoc.parentWindow
    Loop While hWin Is Nothing

    ThisFails = hWin.localStorage.getItem(sLocalStorageVarName)


End Function