Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // http://stackoverflow.com/questions/18342200/how-do-i-call-eval-in-ie-from-c/18349546//
- //
- #include <tchar.h>
- #include <ExDisp.h>
- #include <mshtml.h>
- #include <dispex.h>
- #include <atlbase.h>
- #include <atlcomcli.h>
- #define _S(a) \
- { HRESULT hr = (a); if (FAILED(hr)) return hr; }
- #define disp_cast(disp) \
- ((CComDispatchDriver&)(void(static_cast<IDispatch*>(disp)), reinterpret_cast<CComDispatchDriver&>(disp)))
- struct ComInit {
- ComInit() { ::CoInitialize(NULL); }
- ~ComInit() { CoUninitialize(); }
- };
- int _tmain(int argc, _TCHAR* argv[])
- {
- ComInit comInit;
- CComPtr<IWebBrowser2> ie;
- _S( ie.CoCreateInstance(L"InternetExplorer.Application", NULL, CLSCTX_LOCAL_SERVER) );
- _S( ie->put_Visible(VARIANT_TRUE) );
- CComVariant ve;
- _S( ie->Navigate2(&CComVariant(L"http://jsfiddle.net/"), &ve, &ve, &ve, &ve) );
- // wait for page to finish loading
- for (;;)
- {
- Sleep(250);
- READYSTATE rs = READYSTATE_UNINITIALIZED;
- ie->get_ReadyState(&rs);
- if ( rs == READYSTATE_COMPLETE )
- break;
- }
- // inject __execScript into the main window
- CComPtr<IDispatch> dispDoc;
- _S( ie->get_Document(&dispDoc) );
- CComPtr<IHTMLDocument2> htmlDoc;
- _S( dispDoc->QueryInterface(&htmlDoc) );
- CComPtr<IHTMLWindow2> htmlWindow;
- _S( htmlDoc->get_parentWindow(&htmlWindow) );
- CComPtr<IDispatchEx> dispexWindow;
- _S( htmlWindow->QueryInterface(&dispexWindow) );
- CComBSTR __execScript("__execScript");
- CComBSTR __execScriptCode(L"(window.__execScript = function(exp) { return eval(exp); }, window.self)");
- DISPID dispid = -1;
- _S( dispexWindow->GetDispID(CComBSTR("eval"), fdexNameCaseSensitive, &dispid) );
- _S( disp_cast(dispexWindow).Invoke1(dispid, &CComVariant(__execScriptCode)) );
- // inject __execScript into the child frame
- WCHAR szCode[1024];
- wsprintfW(szCode, L"document.all.tags(\"iframe\")[0].contentWindow.eval(\"%ls\")", __execScriptCode.m_str);
- dispid = -1;
- _S( dispexWindow->GetDispID(__execScript, fdexNameCaseSensitive, &dispid) );
- CComVariant vIframe;
- _S( disp_cast(dispexWindow).Invoke1(dispid, &CComVariant(szCode), &vIframe) ); // inject __execScript and return the iframe's window object
- _S( vIframe.ChangeType(VT_DISPATCH) );
- CComPtr<IDispatchEx> dispexIframe;
- _S( V_DISPATCH(&vIframe)->QueryInterface(&dispexIframe) );
- dispid = -1;
- _S( dispexIframe->GetDispID(__execScript, fdexNameCaseSensitive, &dispid) );
- _S( disp_cast(dispexIframe).Invoke1(dispid, &CComVariant("alert(document.URL)")) ); // call the code inside child iframe
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement