Simulate a click from a IWebBrowser2 control

sachelis used Ask the Experts™
I have a IWebBrowser2 control in MFC (so it's a CWebbrowser_ctrl). I've loaded a page into the control that contains a link that executes javascript:

<a href="javascript:;" class="classname" id="E">Link Text</a>

How can I programmically (from withing MFC) simulate a click on the Link Text?

Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2012
Take a look at ("JavaScript call from C++") - the article covers hat scenario and comes with full source code.
Recently I worked to implement Google Maps on my MFC software.
I had troubles using Javascript call from CHtmlView and from IWebBrowser2 control.

After many research ad headaches, the best full-working solution I found is using CDHtmlDialog (even created without borders ad placed inside a CWnd) which simplify the Javascipt call and seems to work with the lastest HTML technology. Look the code posted for example.

Hope this helps.


void CDlgGoogleMaps::addMarker(int type, int id, LPCSTR lat, LPCSTR lng, LPCSTR text)
	CString sss;
	sss.Format("javascript:myCGMap.addMarker(%d,%d,'%s','%s','%s')", type, id, lat, lng, text);

//      I tried to use Navigate2 to call the Javascript, but my experience is that after multiple calls it hangs or does not work
//	Navigate2(sss, NULL, NULL, NULL, NULL);

void CDlgGoogleMaps::callJavaScript(CString *javasctiptcode)
	if(!bInit) return;
	CString LangStr = _T("javascript");
	VARIANT vEmpty = {0};
	CComPtr<IHTMLDocument2> HTML2Doc;
	CComPtr<IHTMLWindow2> HTML2Wind;
	if(HTML2Doc) HTML2Doc->get_parentWindow(&HTML2Wind);    
	if(HTML2Wind) HTML2Wind->execScript(javasctiptcode->AllocSysString(), LangStr.AllocSysString(), &vEmpty);

Open in new window

Maybe is useful to know that using a CDHtmlDialog, before to make Javascript call, you should Navigate to you local or remote Web Page.
BOOL CDlgGoogleMaps::OnInitDialog()

	CString snavigate = GetMapsDir();

	if(!snavigate.IsEmpty()) { // your html web page
		Navigate(snavigate, NULL, NULL, NULL, NULL);
		bInit = TRUE;
		return TRUE;

	return FALSE;

Open in new window

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial