Click here to Skip to main content
15,881,559 members
Articles / Desktop Programming / Win32
Article

JavaScript function access from plain C++: An example

Rate me:
Please Sign up or sign in to vote.
4.31/5 (8 votes)
24 Aug 2008CPOL1 min read 46.1K   1.1K   29   9
How to execute JavaScript functions with parameters from C++ code.

Image 1

Introduction

How can we execute JavaScript functions from C++, a question I asked a long time ago. But, recently, when I needed an interface between a C++ code and a JavaScript function within an HTML page, I decided to code in search of an answer to that question.

Using the code

For this solution, we have a file called "daveWare.html" located in the same directory/path as the *.exe of this program. The JavaScript function in this html page is:

JavaScript
.........

<script type="text/javascript">

function message(messagestring)
{
    alert(messagestring);

}

</script>

........

The solution, just one of many solutions, is to interface the HTML page/document using a COM/ATL interface, the IWebBrowser2 interface within the dWebCtrl class.

With this interface and its method "Navigate", we can navigate URLs and execute JavaScript (using javascript:) codes in the URLs, as follows:

C++
///-///////////////////////////////////////////////////////////////////
///    Execute string "Script"
///-///////////////////////////////////////////////////////////////////
void dWebCtrl::ExecuteScript(char* Script)
{
    BSTR bstrScript;
    BSTR bufferScript;
    static DWORD size=0;
    char nameInput[256]={'\0'};

    memset(nameInput,'\0',sizeof(nameInput)-1);

    wsprintf(nameInput,"javascript:%s",Script);
    
    size = MultiByteToWideChar(CP_ACP, 0, nameInput, -1, 0, 0);
    if (!(bufferScript = 
         (wchar_t *)GlobalAlloc(GMEM_FIXED, sizeof(wchar_t)*size)))
        return;

    MultiByteToWideChar(CP_ACP, 0, nameInput, -1, bufferScript, size);
    bstrScript = SysAllocString(bufferScript);

    SysFreeString(bufferScript);

    pIwb->Navigate(bstrScript, &vEmpty, &vEmpty, &vEmpty, &vEmpty);
    SysFreeString(bstrScript);

    return;
}

That's it. In our main process, we can access any JavaScript function and pass any parameter to it from our C++ code:

C++
///-//////////////////////////////////////////////////////////////
///         Windows Procedure
///-//////////////////////////////////////////////////////////////
LRESULT CALLBACK WindowProcedure (HWND hwnd, UINT message, 
                                  WPARAM wParam, LPARAM lParam)
{

    switch (message)
    /* handle the messages */
    {
        case WM_COMMAND:
            switch LOWORD(wParam)
            {
                case IDM_COMMAND_ALERT:
                    // execute the function "message" with parameter
                    // "David is the best" within the page "daveware.html" called 
                    // in our dWebCtrl
                    WebBrowser.ExecuteScript("javascript:message('David is the best');");
                    break;

                case IDM_FILE_EXIT:
                    SendMessage(hwnd,WM_DESTROY,(WPARAM)0,(LPARAM)0);
                    break;

            }

            break;

        case WM_CREATE:
        {
            GetCurrentDirectory(MAX_PATH-1,szDirectorioTrabajo);

            WebBrowser.Iniciar(hwnd,hInst);
            break;
        }

        case WM_SIZE:

            WebBrowser.OnResize(0,0);
            break;


        case WM_QUIT:
        case WM_DESTROY:
            /* send a WM_QUIT to the message queue */
            PostQuitMessage (0);
            break;


        default:   /* for messages that we don't deal with */
            return DefWindowProc (hwnd, message, wParam, lParam);
    }

    return 0;
}

Now, you can interface your C++ code with any JavaScript function located in any HTML page (you must know how the JavaScript function works, of course). My next step, access JavaScript "var" defined variables from C++. Any advice?

Best regards to all, and good luck with this stuff. My e-mail address. My URL.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer TeleTracking SAC
Peru Peru
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questionstring length Pin
Member 964262728-May-21 12:03
Member 964262728-May-21 12:03 
QuestionCalling JS functions Pin
Member 1038855427-Jan-14 4:02
Member 1038855427-Jan-14 4:02 
Hi,

Your example is great, however if you have a large param it won't work because of the url size limit. To your knowledge is there any way around this?

Thanks in advance.
AnswerRe: Calling JS functions Pin
davemaster994-Apr-14 18:45
davemaster994-Apr-14 18:45 
Questionwhich compilier to use? Pin
manojratnayake2-Feb-11 7:21
manojratnayake2-Feb-11 7:21 
GeneralGood job Pin
ericpxz25-Aug-08 15:42
ericpxz25-Aug-08 15:42 
GeneralRe: Good job Pin
davemaster9925-Aug-08 17:36
davemaster9925-Aug-08 17:36 
Generalspidermonkey Pin
norbert_barbosa26-Aug-08 0:38
norbert_barbosa26-Aug-08 0:38 
GeneralRe: spidermonkey Pin
davemaster991-Sep-08 23:21
davemaster991-Sep-08 23:21 
QuestionRe: spidermonkey Pin
gh071628-Nov-12 14:16
gh071628-Nov-12 14:16 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.