从运行在 Web 浏览器控件中的 JavaScript 脚本调用 C++ 函数 [英] Calling C++ function from JavaScript script running in a web browser control

查看:17
本文介绍了从运行在 Web 浏览器控件中的 JavaScript 脚本调用 C++ 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的 c++ 应用程序中嵌入了一个 Web 浏览器控件.我希望在 Web 浏览器控件中运行的 javascript 能够调用 c++ 函数/方法.

I have embedded a web browser control in my c++ application. I want javascript running in the web browser control to be able to call a c++ function/method.

我发现了三种方法可以做到这一点:

I have found mentions of three ways to do this:

  1. 实现一个充当中间人的 ActiveX 组件.(此处的实施细节:http://blogs.msdn.com/b/nicd/archive/2007/04/18/calling-into-your-bho-from-a-client-script.aspx)
  2. 使用 window.external.(也在上面的链接中讨论过,但没有提供实现)
  3. 向窗口对象添加自定义对象

我想选择第三个选项,但我还没有找到任何可行的例子来说明如何做到这一点.有人可以告诉我怎么做,或者链接到网上某个地方的工作示例.

I want to go with the third option, but I haven't found any working examples on how to do that. Can someone please show me how to do it, or link to a working example on the net somewhere.

我发现的最接近示例的是 Igor Tandetnik 在 webbrowser_ctl 新闻组中的一个线程.但恐怕我需要更多的帮助.

The closest to an example that I have found is the first reply by Igor Tandetnik in a thread in the webbrowser_ctl news group. But I'm afraid I need more help than that.

我正在嵌入一个 IWebBrowser2 控件,但我没有使用 MFC、ATL 或 WTL.

I'm embedding an IWebBrowser2 control and I am not using MFC, ATL or WTL.

通过 Igor 在我之前链接的线程中给出的伪代码,以及代码项目文章中找到的代码从 C++ 创建 JavaScript 数组和其他对象" 我已经生成了一些代码.

Going by the pseudo-code given by Igor in the thread I linked earlier, and code found in the codeproject article "Creating JavaScript arrays and other objects from C++" I've produced some code.

void WebForm::AddCustomObject(IDispatch *custObj, std::string name)
{
    IHTMLDocument2 *doc = GetDoc();
    IHTMLWindow2 *win = NULL;
    doc->get_parentWindow(&win);

    if (win == NULL) {
        return;
    }

    IDispatchEx *winEx;
    win->QueryInterface(&winEx);

    if (winEx == NULL) {
        return;
    }

    int lenW = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, name.c_str(), -1, NULL, 0);
    BSTR objName = SysAllocStringLen(0, lenW);
    MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, name.c_str(), -1, objName, lenW);

    DISPID dispid; 
    HRESULT hr = winEx->GetDispID(objName, fdexNameEnsure, &dispid);

    SysFreeString(objName);

    if (FAILED(hr)) {
        return;
    }

    DISPID namedArgs[] = {DISPID_PROPERTYPUT};
    DISPPARAMS params;
    params.rgvarg = new VARIANT[1];
    params.rgvarg[0].pdispVal = custObj;
    params.rgvarg[0].vt = VT_DISPATCH;
    params.rgdispidNamedArgs = namedArgs;
    params.cArgs = 1;
    params.cNamedArgs = 1;

    hr = winEx->InvokeEx(dispid, LOCALE_USER_DEFAULT, DISPATCH_PROPERTYPUT, &params, NULL, NULL, NULL); 

    if (FAILED(hr)) {
        return;
    }
}

上面的代码一直运行,所以到目前为止一切看起来都很好.

The code above runs all the way through, so everything looks alright that far.

当我收到作为 *custObj 传递的 DISPID_NAVIGATECOMPLETE2 DWebBrowserEvents2 事件时调用 AddCustomObject:

I call AddCustomObject when I receive the DISPID_NAVIGATECOMPLETE2 DWebBrowserEvents2 event passing this as *custObj:

class JSObject : public IDispatch {
private:
    long ref;

public:
    // IUnknown
    virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppv);
    virtual ULONG STDMETHODCALLTYPE AddRef();
    virtual ULONG STDMETHODCALLTYPE Release();

    // IDispatch
    virtual HRESULT STDMETHODCALLTYPE GetTypeInfoCount(UINT *pctinfo);
    virtual HRESULT STDMETHODCALLTYPE GetTypeInfo(UINT iTInfo, LCID lcid,
        ITypeInfo **ppTInfo);
    virtual HRESULT STDMETHODCALLTYPE GetIDsOfNames(REFIID riid,
        LPOLESTR *rgszNames, UINT cNames, LCID lcid, DISPID *rgDispId);
    virtual HRESULT STDMETHODCALLTYPE Invoke(DISPID dispIdMember, REFIID riid,
        LCID lcid, WORD wFlags, DISPPARAMS *Params, VARIANT *pVarResult,
        EXCEPINFO *pExcepInfo, UINT *puArgErr);
};

值得注意的实现可能是

HRESULT STDMETHODCALLTYPE JSObject::QueryInterface(REFIID riid, void **ppv)
{
    *ppv = NULL;

    if (riid == IID_IUnknown || riid == IID_IDispatch) {
        *ppv = static_cast<IDispatch*>(this);
    }

    if (*ppv != NULL) {
        AddRef();
        return S_OK;
    }

    return E_NOINTERFACE;
}

HRESULT STDMETHODCALLTYPE JSObject::Invoke(DISPID dispIdMember, REFIID riid,
    LCID lcid, WORD wFlags, DISPPARAMS *Params, VARIANT *pVarResult,
    EXCEPINFO *pExcepInfo, UINT *puArgErr)
{
    MessageBox(NULL, "Invoke", "JSObject", MB_OK);
    return DISP_E_MEMBERNOTFOUND;
}

不幸的是,当我尝试使用 javascript 代码中的JSObject"对象时,我从未收到Invoke"消息框.

Unfortunately I never get the "Invoke" message box when I try to use the "JSObject" object from the javascript code.

JSObject.randomFunctionName();  // This should give me the c++ "Invoke" message
                                // box, but it doesn't

编辑 2:

我像这样实现了 GetIDsOfNames:

HRESULT STDMETHODCALLTYPE JSObject::GetIDsOfNames(REFIID riid,
    LPOLESTR *rgszNames, UINT cNames, LCID lcid, DISPID *rgDispId)
{
    HRESULT hr = S_OK;

    for (UINT i = 0; i < cNames; i++) {
        std::map<std::wstring, DISPID>::iterator iter = idMap.find(rgszNames[i]);
        if (iter != idMap.end()) {
            rgDispId[i] = iter->second;
        } else {
            rgDispId[i] = DISPID_UNKNOWN;
            hr = DISP_E_UNKNOWNNAME;
        }
    }

    return hr;
}

这是我的构造函数

JSObject::JSObject() : ref(0)
{
    idMap.insert(std::make_pair(L"execute", DISPID_USER_EXECUTE));
    idMap.insert(std::make_pair(L"writefile", DISPID_USER_WRITEFILE));
    idMap.insert(std::make_pair(L"readfile", DISPID_USER_READFILE));
}

将 DISPID_USER_* 常量定义为私有类成员

with the DISPID_USER_* constants defined as private class members

class JSObject : public IDispatch {
private:
    static const DISPID DISPID_USER_EXECUTE = DISPID_VALUE + 1;
    static const DISPID DISPID_USER_WRITEFILE = DISPID_VALUE + 2;
    static const DISPID DISPID_USER_READFILE = DISPID_VALUE + 3;

    // ...
};

编辑 3、4 和 5:

移至一个单独的问题

编辑 6:

从返回字符串"中提出一个单独的问题编辑.这样我就可以接受 Georg 的 回复,因为它回答了原始问题.

Made a separate question out of the "returning a string" edits. That way I can accept Georg's reply as that answers the original question.

编辑 7:

我收到了一些关于完全工作、自包含的示例实现的请求.这里是:https://github.com/Tobbe/CppIEEmbed.如果可以的话,请分叉和改进:)

I have gotten a few requests for a fully working, self contained, example implementation. Here it is: https://github.com/Tobbe/CppIEEmbed. Please fork and improve if you can :)

推荐答案

您需要实现 GetIDsOfNames() 来做一些明智的事情,因为该函数将在 Invoke().
如果您的接口位于类型库中,请参阅此处作为示例.如果您想改用后期绑定,可以使用 DISPIDs 大于 DISPID_VALUE 且小于 0x80010000(所有值 <= 0 且在 0x80010000 范围内0x8001FFFF 保留):

You need to implement GetIDsOfNames() to do something sensible as that function will be called by client code before Invoke().
If you have your interfaces in a type library see here for an example. If you want to use late-binding instead, you can use DISPIDs greater DISPID_VALUE and less than 0x80010000 (all values <= 0 and in the range 0x80010000 through 0x8001FFFF are reserved):

HRESULT GetIDsOfNames(REFIID riid, LPOLESTR *rgszNames, UINT cNames, 
                      LCID lcid, DISPID *rgDispId)
{
    HR hr = S_OK;
    for (UINT i=0; i<cNames; ++i) {
        if (validName(rgszNames)) {
            rgDispId[i] = dispIdForName(rgszNames);
        } else {
            rgDispId[i] = DISPID_UNKNOWN;
            hr = DISP_E_UNKNOWNNAME;
        }
    }
    return hr;
}

HRESULT Invoke(DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, 
               DISPPARAMS *Params, VARIANT *pVarResult, EXCEPINFO *pExcepInfo, 
               UINT *puArgErr)
{
    if (wFlags & DISPATCH_METHOD) {
       // handle according to DISPID ...
    }

    // ...

请注意,DISPID 不应该突然改变,例如应使用静态 map 或常量值.

Note that the DISPIDs are not supposed to change suddenly, so e.g. a static map or constant values should be used.

这篇关于从运行在 Web 浏览器控件中的 JavaScript 脚本调用 C++ 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆