tt9
tt9

Reputation: 6069

IWebBrowser2.Document not returning IHTMLDocument2

I am trying to cast an IWebBrowser2 COM object into a IHTMLDocument2 so that I can manipulate the contents of the IE web browser.

Here is the start of my code:

int main()
{
    if (SUCCEEDED(OleInitialize(NULL)))
    {
        CComQIPtr<IWebBrowser2> pBrowser2;
        CComQIPtr<IDispatch> pDispatch;

        CoCreateInstance(CLSID_InternetExplorer, NULL, CLSCTX_LOCAL_SERVER,
            IID_IWebBrowser2, (void**)&pBrowser2);
        if (pBrowser2)
        {    
            //Here, pDispatch remains null and hr == E_FAIL
            HRESULT hr = pBrowser2->get_Document(&pDispatch);
        }
        OleUninitialize();
    }    
}

At the call to IWebBrowser2::get_Document() the pDispatch variable remains null and the returned HRESULT is E_FAIL.

What do I need to do to get the IHTMLDocument2 object from the IWebBrowser2?

Upvotes: 1

Views: 1138

Answers (1)

Barmak Shemirani
Barmak Shemirani

Reputation: 31599

Call Navigate to open a webpage first. Otherwise there is no document to get.

if (pBrowser2)
{
    VARIANT vEmpty;
    VariantInit(&vEmpty);

    BSTR str = SysAllocString(L"http://google.com");
    HRESULT hr = pBrowser2->Navigate(str , &vEmpty, &vEmpty, &vEmpty, &vEmpty);
    if (SUCCEEDED(hr))
    {
        //optional: show the explorer window
        //pBrowser2->put_Visible(VARIANT_TRUE);

        hr = pBrowser2->get_Document(&pDispatch);
        if (hr == S_OK)
            OutputDebugStringW(L"okay\n");
    }

    SysFreeString(str);
    pBrowser2->Quit();
}

Upvotes: 2

Related Questions