How to find and call javascript method from vba

Here simple example which uses execScript method of the window object. It calls a global functions named myFunc and myFuncWithParams. Code was tested with IE 11.

Option Explicit

Private Const Url As String = "c:\Temp\evalExample.html"

Public Sub Test()
    Dim objIE As SHDocVw.InternetExplorer
    Dim currentWindow As HTMLWindowProxy

    Set objIE = New SHDocVw.InternetExplorer
    objIE.navigate Url
    objIE.Visible = 1

    Do While objIE.readyState <> 4
        DoEvents
    Loop

    Set currentWindow = objIE.document.parentWindow

    ' Here the function without parameters is called.
    currentWindow.execScript code:="myFunc()"

    ' Here the function with parameters is called.
    ' First parameter is numeric, then string, then boolean and finally object.
    ' The object has three properties, numeric, string and array.
    currentWindow.execScript code:="myFuncWithParams(123, 'Some text', true, { property1: 555, property2: 'hi there from object', property3: [111,222,333] })"

    ' And here function which receives parameters and returns value.
    ' The return value is then available through hidden property of document named 'Script'.
    ' Thanks to this answer: https://stackoverflow.com/questions/9005914/retrieve-return-value-of-a-javascript-function-in-the-webbrowser-control-in-vb6
    currentWindow.execScript code:="func = function(){return myFuncReturns(2,3);}; retVal = func();"
    Dim result As Long
    result = objIE.document.Script.retVal
    Debug.Print result ' for 2 and 3 prints 5

    objIE.Quit
    Set objIE = Nothing
 End Sub

evalExample.html

<!-- saved from url=(0016)http://localhost -->
<html>
<head>
    <script type="text/javascript">
        function myFunc() {
            var date = new Date();
            alert("Hi from my parameter-less 'myFunc'. Day of the month: " + date.getDate());
        }

        function myFuncWithParams(a, b, c, d) {
            var number = a + 100,
                text = b + " from my func2",
                bool = !c,
                obj = d;

            var alertText = "\nNumber="" + number + """ +
                            "\nText="" + text + """ +
                            "\nBoolean = '" + bool + "'" +
                            "\nObject.property1 = '" + obj.property1 + "'" +
                            "\nObject.property2 = '" + obj.property2 + "'" +
                            "\nObject.property3.lenght="" + obj.property3.length + """ + 
                            "\nObject.property3[2] = '" + obj.property3[2] + "'";

            alert("Hi from my 'myFunc2' with parameters.\n" + alertText);
        }

        function myFuncReturns(a, b) {
            return a + b;
        }
    </script>
</head>
<body>
    <div>eval test</div>
</body>
</html>

Leave a Comment