2016-04-26 16 views
6

Ho visto questo per le estensioni BHO, in cui il JavaScript può chiamare le funzioni nel BHO C++. Ma lascia dire che non sto usando un BHO, invece ho un'applicazione console C++ che crea un oggetto COM IE in questo modo:Uso di Javascript per chiamare C++ in Internet Explorer

HRESULT hr = CoCreateInstance(
      CLSID_InternetExplorer, 
      NULL, 
      CLSCTX_LOCAL_SERVER, 
      IID_IWebBrowser2, 
      (void**)&_cBrowser); 

Ho anche una classe che "possiede" l'oggetto IWebBrowser2 che ritorna da questa funzione.

class BrowserWrapper{ 
    public: 
     CComPtr<IWebBrowser2> pBrowser; 

     void SomeFunction(...) 
} 

C'è un modo per chiamare una funzione come "SomeFunction" nella classe wrapper dal JavaScript dell'oggetto IWebBrowser2 generato?

risposta

5

È necessario implementare il IDocHostUIHandler interface e impostare il browser web con un codice simile a questo (estratto dal doc):

ComPtr<IDispatch> spDocument; 
hr = spWebBrowser2->get_Document(&spDocument); 
if (SUCCEEDED(hr) && (spDocument != nullptr)) 
{ 
    // Request default handler from MSHTML client site 
    ComPtr<IOleObject> spOleObject; 
    if (SUCCEEDED(spDocument.As(&spOleObject))) 
    { 
     ComPtr<IOleClientSite> spClientSite; 
     hr = spOleObject->GetClientSite(&spClientSite); 
     if (SUCCEEDED(hr) && spClientSite) 
     { 
      // Save pointer for delegation to default 
      m_spDefaultDocHostUIHandler = spClientSite; 
     } 
    } 

    // Set the new custom IDocHostUIHandler 
    ComPtr<ICustomDoc> spCustomDoc; 
    if (SUCCEEDED(spDocument.As(&spCustomDoc))) 
    { 
     // NOTE: spHandler is user-defined class 
     spCustomDoc->SetUIHandler(spHandler.Get()); 
    } 
} 

Devi specificamente implementare il GetExternal method

Ora, in IE di javascript (o VBScript per questo), è possibile accedere il vostro ospite con una chiamata del genere:

var ext = window.external; // this will call your host's IDocHostUIHandler.GetExternal method 
ext.SomeFunction(...); // implemented by your object 

Cosa si torna in GetExt ernal deve essere un oggetto IDispatch che è possibile progettare nel modo desiderato.

0

È necessario implementare l'interfaccia IDocHostUIHandler. Questo ha un metodo chiamato GetExternal - che è necessario restituire un oggetto che implementa IDispatch.

In JavaScript, è possibile chiamare window.external.something() - che farà sì che il browser per interrogare per l'implementazione esterna - l'oggetto IDispatch - e sarà quindi utilizzare il IDispatch per eseguire something.

Problemi correlati