Browser integration-add macro support to browser programs

Source: Internet
Author: User
Tags knowledge base
Browser Integration Teaching-add macro support to browser programs

This tutorial provides a method to add macro support to a browser program. You will see how to add macro support to the MFC program. This article also discusses how to expand the chtmlview function in vc6, how to implement the MDI structure browser, and how to analyze the DHTML document structure.

Click here to download the code of this Article

This article consists of the following parts:

  1. Prerequisites and requirements
  2. Introduction
  3. Activity script
  4. Add script support for applications
  5. Security
  6. Chtmlview Enhancement
  7. Script example
  8. Conclusion
  9. Reference
Prerequisites and requirements

Before reading this article, we recommend that you

  • For Microsoft basic class (MFC) and Component Object Model (Com) Understanding
  • Familiar with activity Template Library (ATL)
  • Install Microsoft Internet Explorer (IE) 6.0 or later
  • Header files and library files with ie6.0 or higher in the Development Environment
Introduction

IntegrationBrowser controlsFor Fast Application Development (Rad) Is a powerful tool; you can use dynamic HTML (DHTML), Or an extensible markup language (XML) Display your user interface. A common purpose is to use it to display a form, and then process the form by analyzing the form webpage and processing the submission event. However, if you want to analyze a single page, the analysis method depends entirely on the page structure. That is to say, if you analyze a webpage through the interface provided by IE in an application, for each webpage structure, you need to write and compile the code once. This is completely normal when the application and form web page are released together, but the form web page is located on a remote server and may be modified sometimes, or to make the application valid for other websites, you must modify and re-release the application at the same time. To avoid repeated application modifications, you can use --

Activity script

You can use activity scripts to write flexible code processing without re-compiling the program. You may have seen activity scripts in many applications, such as IE, Microsoft Office, and Visual Studio. In the Platform SDK (Platform SDKIn Microsoft Windows Script technologies, this section describes the concept, background, architecture, and call steps of the activity script.

If you need sample code, you can search for the kbaxscript keyword in the Microsoft Knowledge Base (KB. Below are some examples

  • Q223139 HOWTO: add support for hosting VBScript to an ATL Application
  • Q182138 sample: axsh.exe demonstrates implementing ActiveX script hosts
  • Q168214 sample: mfcaxs.exe implements an ActiveX Script Host Using MFC

  • Q223389 file: scriptng.exe contains the files necessary for implementing ActiveX script hosts and engines

  • Q232394 HOWTO: Catch run-time errors in an ActiveX Script Host

The sample code in this article is based on mfc6, so the Code provided in q168214 is used.

Add scripts for applications to support automated objects

To implement script support, we need to enable automated server support for applications. The simplest way to implement this support is to useMFC Application Wizard(Application Wizard) when creating an ieautomation MDI application, select automation support in step 3 of the MDI wizard.

The chtmlview derived class cieautomationview automatically generated by the Wizard is not an Automation Object. Therefore, when creating a sample project, I delete the definition and implementation file of cieautomationview, and then delete the cieautomationview information in the Class Wizard, re-create cieautomationview class, specify the base class as chtmlview during creation and support automation.

The script interpreter in cieautomationview was modified from the sample code of q168214, removing some objects and adding the implementation of Dom extension objects.

Scripter object

Script Engine object, which can be accessed by scripter. Provides methods for creating objects.

Webbrowser object

Browser control object, which can be accessed by webbrowser. It can be used to access the Document Object Model. The view source code function is also enhanced to display the Document Object Model. For more information, see the reference at the end of this article.

External Object

Dom extension object, which can be accessed by the name external. Object used to expand the Document Object Model of the browser. In this example, I also use this object to forward events of the webbrowser object. Although most of the functions are implemented, there seems to be some problems with the automatic completion function, which seems to be related to the ishelluihelper's undisclosed autocompleteattatch method. (In fact, the browser control needs to implement idochostuihandler: gethostinfo, refer to the http://blog.joycode.com/jiangsheng/archive/2004/01/08/11037.aspx)

Type Library support

In the script, the object type library information is required to access the attributes, methods, and events of the object. By default, classes derived directly from ccomtarget cannot be added or deleted through the Class Wizard. The ccomtargetex class "simulates" Some ActiveX features, and spoofed the Class Wizard to do this. When adding type information to an object, add the Type Library of the application to the resource by referring to q185720 HOWTO: Provide type information from an MFC Automation server.

Security

Although the automated browser can provide more flexibility, it also exposes part of the application to users. For example, you may modify the script to make the application abnormal. In addition, if you can view scripts, you can understand the program structure and attack sites that are not carefully designed.

Using scripts to create objects may also cause security issues. Some objects are not secure, such as malicious or incorrectly used COM objects.

If Dom is extended so that scripts on the web page can access the functions of the application, you must ensure that the script is secure or comes from a trusted site. The following function is used to check the security before accessing the extended properties of window in Dom.

Bool cieautomationview: canaccessexternal ()
{
// If the dispatch we have is safe,
// We allow access
If (isexternaldispatchsafe ())
Return true;

// The external dispatch is not safe, so we check
// Whether the current zone allows for Scripting
// Of objects that are not safe for scripting
If (m_sphtmldoc = NULL)
Return false;

Ccomptr <iinternethostsecuritymanager> spsecman;
M_sphtmldoc-> QueryInterface (iid_iinternethostsecuritymanager,
(Void **) & spsecman );
If (spsecman = NULL)
Return false;

Hresult hR = spsecman-> processurlaction (urlaction_activex_override_object_safety,
Null, 0, null, 0, 0, puaf_default );
If (hR = s_ OK)
Return true;
Return false;
}
By default, scripts on a web page can access webpages on the same site.

Enhanced chtmlview use advanced host features

For the benefits of using advanced host features, see my translated csdn document center articleCustom Browser. In the sample code in this article, I used this feature to extend the DHTML document structure model (Dom),Allows scripts on the webpage to access the application. For the implementation of the offline browsing function, refer to this article.

To use advanced host features to customize browsers Based on the chtmlview of mfc6, You need to reload the default control client site (this code is only necessary in mfc6, the chtmlview of mfc7 already supports advanced host features ). Because mfc6 cannot overload the virtual function createcontrolsite of cwnd to create a custom customer site, q236312 HOWTO: Disable the default pop-up menu for chtmlview is used, reload the default control client site manager. Then, save the pointer of the Control Host in the reloaded default control client site.

CCustomControlSite::CCustomControlSite(COleControlContainer *pCnt):COleControlSite(pCnt){ m_pCustomImpl=NULL; CWnd* pWnd=pCnt->m_pWnd; if(pWnd){  if(pWnd->IsKindOf(RUNTIME_CLASS(CIEAutomationView))){  CIEAutomationView* pView=(CIEAutomationView*)pWnd;  m_pCustomImpl=pView; } }

In this way, you can call the corresponding processing of the Control Host in the idochostuihandler2 Implementation of the control customer site, for example

HRESULT FAR EXPORT CCustomControlSite::XDocHostUIHandler2::GetHostInfo( DOCHOSTUIINFO* pInfo ){ METHOD_PROLOGUE(CCustomControlSite, DocHostUIHandler2) if(pThis->m_pCustomImpl){  return pThis->m_pCustomImpl->GetHostInfo(pInfo ); } return S_OK;}

One application of the advanced host feature is Dom extension, which allows scripts on the Web page to access Dom extension objects using window. External. The Dom extension object implemented by IE has the menuarguments attribute and the ishelluihelper interface.

Control new window

By default, the browser opens a new window in IE when receiving a new window creation request. You can process the newwindow2 event to open the request page in the specified window.

void CIEAutomationView::OnNewWindow2(LPDISPATCH* ppDisp, BOOL* Cancel) 
{ 
 // Get a pointer to the application object. 
 CWinApp* pApp = AfxGetApp(); 
 // Get the correct document template. 
 POSITION pos = pApp->GetFirstDocTemplatePosition(); 
 CDocTemplate* pDocTemplate = pApp->GetNextDocTemplate( pos ); 
 // Create a new frame. 
 CFrameWnd* pFrame = pDocTemplate->CreateNewFrame( 
  GetDocument(), 
  (CFrameWnd*)AfxGetMainWnd() ); 
 // Activate the frame. 
 pDocTemplate->InitialUpdateFrame( pFrame, NULL ); 
 CIEAutomationView* pView = (CIEAutomationView*)pFrame->GetActiveView(); 
 // Pass pointer of WebBrowser object. 
 pView->SetRegisterAsBrowser( TRUE ); 
 *ppDisp = pView->GetApplication(); 
} 

For more information, see q184876 HOWTO: Use the webbrowser control newwindow2 event ..

MDI Browser

The sample code in this article is based on a browser. For convenience, you can directlyMfcieThe sample is modified and changed to the MDI structure. Mfcie is a simple browser, but there is a small problem after code is transferred from the main framework to the sub-framework, and the dynamically created favorites menu is gone. This is because the menu replacement mechanism of the MDI framework restores the default menu when the framework is activated, so I have overloaded the cdocument: getdefaultmenu, restore the modified menu when replacing the menu of the MDI framework (see ). To obtain the document pointer during the Sub-framework creation process to modify the menu saved in the document, you can obtain the MDI creation context from the creation structure.

MDICREATESTRUCT * pMDICreateStruct=(MDICREATESTRUCT * )lpCreateStruct->lpCreateParams;CCreateContext *pCreateContext=(CCreateContext *)pMDICreateStruct->lParam;pMenu =((CIEAutomationDoc *)pCreateContext->m_pCurrentDoc)->m_menuDefault.GetSubMenu(3);
Favorites

The mfcie example demonstrates how to create a favorites menu. However, a problem occurs when the favorites command is displayed in the toolbar to the MDI sub-framework. The position of the dynamically created favorites menu is not fixed. However, you can find the new "add to Favorites" command to locate the menu. The function of adding to favorites and managing favorites is implemented by creating a shelluihelper object.

Automatic completion

For ease of use, I also added the auto-completion function in the application. The implementation of the Automatic completion function in the address bar is relatively simple. You can call the system's API shautocomplete. When I expanded the DOM myself, the automatic completion of the form seemed to be a problem.

For more information, refer to the csdn document center article I translated to integrate the Automatic completion function in the application.

Access the site to which authorization is required

Some sites need to verify the user identity when accessing, but by default, the browser control does not prompt the user to enter the user name and password when the user identity cannot be verified. The iserviceprovider interface is implemented at the customer site of the control, and the iauthenticate interface is also implemented to enable the application to enter authentication information. For more information, see the Microsoft Knowledge Base Article q329802 error: proxy authentication via iauthenticate may fail on the secure URL.

Common command processing

For ease of use, the function of calling the Search dialog box, viewing source code, and setting Internet Options is added. This is achieved by querying the iolecommandtarget interface of the browser control and executing the Command Group cgid_webbrowser. There are more than one method to implement such commands, such as loading inetcpl. CPL: Call the launchinternetcontrolpanel function to enable Internet Options. Use the imarkupservices interface to perform search, locate, and select, and use a stream to obtain/set webpage content. The sample code shows how to analyze the document structure and edit the HTML code or framework source file of the selected webpage element.

Mfc6bug fixing

Although the application can already have relatively complete functions, in order to make the application work normally for a long time, it is necessary to fix some problems in mfc6. I will only list the article titles here. If you are interested, you can view the articles in the Microsoft Knowledge Base or the code in this article.

  • Q241750 BUG: chtmlview leaks memory by not releasing bstrs in several methods
  • Q220021 BUG: chtmlview does not repaint correctly in an Appwizard-generated MDI Application
  • Q253219 PRB: webbrowser control disappears when script callwindow. Close ()
Script example
WebBrowser.Navigate "About:<H1><B>This is a test</B>
Dim msword Set msword = Scripter.HostCreateObject("Word.Basic")msword.appshowmsword.filenewmsword.Insert "hello"
Sub External_BeforeNavigate2(pDisp, URL, Flags, TargetFrameName, PostData, Headers, Cancel)MsgBox URLEnd Sub

If you write scripts for the webbrowser object events, you will find that the event processing code is not executed because chtmlview processes these events. You can trigger the corresponding events of the defined object in the processing code of your chtmlview derived class. In the sample code, I forwarded the beforenavigate2 event to the event of the custom object.

 

Conclusion

Adding script support to applications can greatly improve the flexibility and scalability of applications. Although it sacrifices performance, security, and the amount of code, this sacrifice is often worthwhile.

Although I did not forward the documentcomplete event in the sample code, it is only based on security considerations. Automated browsers can easily implement scripts such as ad window filtering, automatic form filling, and page analysis. Writing these scripts depends on your own needs.

Reference
  • Browser

    • About the browser
    • Reusing mshtml
    • Webbrowser customization (Custom Browser)
    • Loading HTML content from a stream (use stream to obtain/set webpage content)
    • Reusing the webbrowser Control
    • Using MFC to host a webbrowser Control
  • Security
    • About cross-frame scripting and security
  • Document Object Model
    • About the DHTML Object Model
    • About the W3C Document Object Model
    • Working with windows, frames, and dialog boxes
  • Automatic completion
    • Using AutoComplete in HTML Forms
    • Integrate the Automatic completion function in the Application

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.