简体   繁体   English

从Web浏览器控件中运行的JavaScript脚本调用C ++函数

[英]Calling C++ function from JavaScript script running in a web browser control

I have embedded a web browser control in my c++ application. 我在我的c ++应用程序中嵌入了一个Web浏览器控件。 I want javascript running in the web browser control to be able to call a c++ function/method. 我希望在Web浏览器控件中运行的javascript能够调用c ++函数/方法。

I have found mentions of three ways to do this: 我发现有三种方法可以做到这一点:

  1. Implement an ActiveX component that acts as a middle man. 实现一个充当中间人的ActiveX组件。 (Implementation details here: http://blogs.msdn.com/b/nicd/archive/2007/04/18/calling-into-your-bho-from-a-client-script.aspx ) (此处的实施细节: http//blogs.msdn.com/b/nicd/archive/2007/04/18/calling-into-your-bho-from-a-client-script.aspx
  2. Use window.external. 使用window.external。 (Also discussed in the link above, but no implementation provided) (也在上面的链接中讨论过,但没有提供实现)
  3. Add a custom object to the window object 将自定义对象添加到窗口对象

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. 有人可以告诉我该怎么做,或链接到某个网上的工作示例。

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 . 最接近我发现的一个例子是Igor Tandetnik在webbrowser_ctl新闻组的一个帖子中的第一个回复。 But I'm afraid I need more help than that. 但我担心我需要更多的帮助。

I'm embedding an IWebBrowser2 control and I am not using MFC, ATL or WTL. 我嵌入了一个IWebBrowser2控件,我没有使用MFC,ATL或WTL。

EDIT: 编辑:

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

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. 上面的代码一直在运行,所以一切看起来都不错。

I call AddCustomObject when I receive the DISPID_NAVIGATECOMPLETE2 DWebBrowserEvents2 event passing this as *custObj : 当我收到DISPID_NAVIGATECOMPLETE2 DWebBrowserEvents2事件并将其作为*custObj传递时,我调用AddCustomObject:

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);
};

Noteworthy implementations might be 值得注意的实现可能是

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;
}

and

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;
}

Unfortunately I never get the "Invoke" message box when I try to use the "JSObject" object from the javascript code. 不幸的是,当我尝试使用javascript代码中的“JSObject”对象时,我从未得到“调用”消息框。

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

EDIT 2: 编辑2:

I implemented GetIDsOfNames like so: 我像这样实现了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;
}

and this is my constructor 这是我的构造函数

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));
}

with the DISPID_USER_* constants defined as private class members 将DISPID_USER_ *常量定义为私有类成员

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;

    // ...
};

EDIT 3, 4 and 5: 编辑3,4和5:

Moved to a separate question 转到单独的问题

EDIT 6: 编辑6:

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. 这样我就可以接受Georg的答复,因为它回答了原来的问题。

EDIT 7: 编辑7:

I have gotten a few requests for a fully working, self contained, example implementation. 我已经收到了一些完全工作,自包含的示例实现的请求。 Here it is: https://github.com/Tobbe/CppIEEmbed . 这是: https//github.com/Tobbe/CppIEEmbed Please fork and improve if you can :) 如果你能:)请分叉和改进:)

You need to implement GetIDsOfNames() to do something sensible as that function will be called by client code before Invoke() . 您需要实现GetIDsOfNames()来做一些合理的事情,因为在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 DISPID s greater DISPID_VALUE and less than 0x80010000 (all values <= 0 and in the range 0x80010000 through 0x8001FFFF are reserved): 如果要使用后期绑定,则可以使用DISPID更大的DISPID_VALUE且小于0x80010000 (所有值<= 0且在0x800100000x8001FFFF范围内保留):

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 ...
    }

    // ...

Note that the DISPID s are not supposed to change suddenly, so eg a static map or constant values should be used. 请注意, DISPID不应突然改变,因此例如应使用静态map或常量值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM