VC interaction with JavaScript (iii) ---- The CWebPage class calls javascript Functions (passing parameters to js functions and returning values)
① You need a class CWebPage written by someone else to add the two files WebPage. h and WebPage. cpp to the project.
② Add the WebBrowser control. In the header file of the View/dialog box class, add the member variable m_webBrowser and call the Navigate () function to load an html page.
③ Add # include "WebPage. h" to the dialog box or view implementation file and call the javascript function in the response function of the button. The Code is as follows:
CWebPage web;
Web. SetDocument (m_webBrowser.GetDocument ());
CComVariant varResult; // stores the return value.
// Note: The parameter must be passed to the string type.
Web. callJScript ("TansTo", m_latitude, m_longbench, & varResult); // call the TansTo () function in JS, pass two parameters (latitude, longitude), and write the return value to varResult
If (varResult. dblVal = 122.211) // double corresponds to dblVal, and integer corresponds to intVal
MessageBox ("variable value retrieved successfully from js ");
④ Define the corresponding function in the script tag of the html file. The specific code is as follows:
<Script type = "text/javascript">
Function TansTo (lat, lng) // go to the specified location. There are two parameters: latitude and longitude.
{
Map. panTo (new GLatLng (lat, lng); // Google map API, jump to the location specified by the coordinates
Return 122.211; // return a double value to varResult
}
</Script>
Note:
(1) In javascript above, the panTo () function is a function in google map API and can be customized according to different needs.
(2) The above implementation does not care about the role of the CWebPage class, just use it. If you want to learn more, please search for articles on "COM Component Automation" and "IDispatch interface.