Using Javascript to Call C ++ in Internet Explorer

I saw this for BHO extensions, where JavaScript can call functions in C ++ BHO. But I will say that I do not use BHO, instead I have a C ++ console application that creates an IE COM object as follows:

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

I also have a class that "owns" the IWebBrowser2 object that returns from this function.

 class BrowserWrapper{ public: CComPtr<IWebBrowser2> pBrowser; void SomeFunction(...) } 

Is there a way to call a function of type SomeFunction in a shell class from JavaScript in the created IWebBrowser2 object?

+6
source share
2 answers

You must implement the IDocHostUIHandler interface and install it in a web browser with code similar to this (extracted from the document):

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

You must specifically implement the GetExternal method

Now, in javascript IE (or vbscript, for that matter), you can access your host with a call like this:

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

What you return to GetExternal should be an IDispatch , which you can design as you want.

+5
source

You need to implement the IDocHostUIHandler interface. This method has a GetExternal method - which you need to return an object that implements IDispatch.

In javascript, you can call window.external.something() - which will cause the browser to request an external implementation - an IDispatch object - and then it will use IDispatch to execute something .

0
source

All Articles