Loading Simple HTML Pages From Memory

Environment: VC6 SP4, IE 5.0, Platform SDK.

Sometimes,when you use web browser control, it's not suitable to work with temporary files as a source for browser navigation. For example, if you want secure information or you need dynamically change content from c++ program.
CMoreHtml class derived from standard MFC-class CHtmlView and fully keeps class functionality. Additionally you will have some more abilities to work with html content. This class use standard COM interfaces IWebBrowser2, IHtmlDocument2. Moreover in this application uses IMarkupServices interface it force to minimum capability with IE 5.0.

Class usage

You could derive your own view from CMoreHtmlView like standard CHtmlView. If you want to activate work with memory, you need just call NavigateMemory() function like showed in example:

void CYourOwnView::OnInitialUpdate()
{
 CHtmlView::OnInitialUpdate();

 // TODO: This code navigates to a popular spot on the web.
 //  change the code to go where you'd like.
 //Navigate2(_T("http://www.microsoft.com/visualc/"),NULL,NULL);

 //initialize  navigation from memory mode
 NavigateMemory();
 
 //set parameters of html
 SetTitle( "Shakespeare page");
 PutBodyContent( (LPSTR)lpcstrContent);
 COleVariant ovBgColor( "cornsilk");
 SetBodyAttributes( "BGCOLOR", ovBgColor);
 SetScript( (LPSTR)lpcstrScript);
}

In any case, you need source for correct working of web browser control. Thereto, you can use html-file template from resource.

<HTML>
  <HEAD>
   <TITLE></TITLE>
   <SCRIPT>>/SCRIPT>
  </HEAD>
  <BODY>
  </BODY>
</HTML>

I can't find possibility to write to <HTML> or <HEAD> tag content, therefore I've created several functions, they write to exact parts of html document.

BOOL PutBodyContent( LPSTR lpstrContent) Write html content ( filling tag).
lpstrContent - text of HTML content;
BOOL SetBodyAttributes(CString sName, ColeVariant vValue) Setting tag attributes, like BGCOLOR, LINK etc.
sNname - attribute name;
vValue - attribute value(VARIANT type);
BOOL SetCharset(LPSTR lpstrCharset) Setting Charset.
BOOL SetScript(LPSTR lpstrScript) Write html scripts.
lpstrScript - content of <SCRIPT> tag;
BOOL SetTitle(LPSTR lpstrTitle) Set title of html document;

Uploading of html content possible only when downloading of html template finished. But you could use these functions in any place of code after running NavigateMemory(). Values of content store in CMoreHtmlView class members and apply in exact moment.

How CMoreHtmlView works.

NavigateMemory() function loads template html document from resource with identifier IDR_EMPTY_HTML and sets m_bMemoryMode to TRUE. PutBodyContent, SetScript etc. functions call IHtmlDocument2 methods only if document object exists, in other case functions only store content in private variables. If these functions execute with NULL parameter then content modification does from member variable values.
OnDownloadComplete function overloading makes for reloading html content if refresh browser command will be called.

Search and mark words in html document

Sometime you need make your own search system in application that uses web browser control. MarkWords member function you could use in that case. You only need to pass a search string as input parameter.

for( ; ;)
{	
 // Find text
 hr = pPtr1->FindText( poSearchStr, 0, pPtr2, NULL );

 if (hr == S_FALSE) // did not find the text
  break;

 IHTMLElement *pFontEl;
 
 // create FONT element with attributes for selection
 OLECHAR pchAttributes=0;
 hr=pMS->CreateElement(TAGID_FONT, 
 L"COLOR=white STYLE=\"backgroundcolor:darkblue\"", &pFontEl);
 
 // Insert created element to context
 hr=pMS->InsertElement( pFontEl, pPtr1, pPtr2);

// Continue searching
pPtr1->MoveToPointer( pPtr2);
}
It's main part of MarkWords function, at the beginning makes search of string after that creates <FONT COLOR=white STYLE="backgroundcolor:darkblue">...</FONT> element. This tag marks the located string.

Downloads

Download demo project and source - 29 Kb


Comments

  • Load xml with xslt from memory

    Posted by alexiworld on 05/14/2004 10:33am

    I have in memory the content of xml file which refers to xslt file on disk. I am trying to force the browser to display this content. But it doesn't work as I expected! :(( Otherwise if I save this content as temporary file on disk and make browser to navigate to new location everything is fine. So can you answer me what to do to make things workings without making temporary file?! Best regards, Alex

    Reply
  • implemented memory table in a dll causes acess violation

    Posted by Legacy on 08/27/2003 12:00am

    Originally posted by: John

    Hello,

    I have taken the sample for a memory html into a dll, where the first call to it succeeds, but a second navigation to the resource from a new instance of the class causes an access violation in urlmon.dll when navigate2 is called.

    Anyone else experience a similar problem ?
    Is the resource getting locked ?

    Thanks,
    John

    Reply
  • This seemed not work correct with Unicode text

    Posted by Legacy on 08/19/2003 12:00am

    Originally posted by: Hung N

    I used this to load a Unicode text, then I don't understand why all the links with <A HREF... are not activated, the text seemed to be displayed as pur plain text in black, with only bigger size for <H?> tags but no color or links

    Any idea ?

    Reply
  • I want to process HTML form with C Program.

    Posted by Legacy on 04/08/2003 12:00am

    Originally posted by: Bhavesh Patel

    Hi Sir,
    I want a program that can process HTML form. CGI Sort of programming.

    With Regards..
    Bhavesh

    Reply
  • Encoding issues

    Posted by Legacy on 03/24/2003 12:00am

    Originally posted by: oren

    When i use the component (as a part of MDI app) and try right clicking on it and change the encoding nothing happends (ie the page reloads so i get another download complete event, but the encoding doesn't change).
    any ideas ?

    Oren

    Reply
  • Need hint. How to programmatically swap contents of two WebBrowsers.

    Posted by Legacy on 02/06/2003 12:00am

    Originally posted by: Oleg Schildt

    Hi,
    
    

    I read your article and thought, maybe you can give me a hint on my problem solution.

    I am making an IE add-in so called SmartViewers for multiple surfing. It is an alternative solution to the tabbed view. The pages are loaded into small browser windows that are found in a bar docked on the left to the main browser (like history and search). The contents of small windows is shown zoomed like it is in the Windows Explorer in the WEB mode. By clicking the small window, its contents and that of the main browser is swapped. My problem is that I can not find a more efficient solution for contents swapping than just simple re-navigation.

    My bar is a COM object that is integrated into IE through a tool button. I have access to the IWebBrowser2 interface of the main browser and so to all other available interfaces.

    The small windows are WebBrowser controls created as follows. CWnd::CreateControl(CLID_WebBrowser...)

    I tried to swap contents using IPersistStream Save/Load, IOleObject GetClientSite/SetClientSite, but nothing really worked.

    I would appritiate any ideas or suggestions.

    Best regards

    Reply
  • A simpler way

    Posted by Legacy on 10/01/2002 12:00am

    Originally posted by: Nom De Plume

    IF all you want to do is change the HTML of your
    
    control there is a much simpler way. More importantly
    it is compatible with IE 4.0+

    Simply do the following:

    void CDerivedClass::setHTML(CString html)
    {
    IHTMLDocument2* pDoc = NULL;
    IHTMLElement* pBody = NULL;
    BSTR htmlBStr = html.AllocSysString();

    GetDHtmlDocument(&pDoc);
    pDoc->get_body(&pBody);
    pBody->put_innerHTML(htmlBStr);

    if ( htmlBStr != NULL )
    SysFreeString(htmlBStr);

    pBody->Release();
    pDoc->Release();
    }

    Simply call like this:

    setHTML("<HTML><BODY>Test!!!</BODY></HTML>");

    Note: I have omitted checking of return values in the
    code for clarity, however, you should certainly do this.
    Also this code works for a CDHTMLDialog derived class,
    but you can modify it for any class that can return an
    IHTMLDocument2 object by using the appropriate function
    in place of the GetDHtmlDocument call above.

    Reply
  • Here is how to add < STYLE > to this!

    Posted by Legacy on 09/30/2002 12:00am

    Originally posted by: Sander Verhagen

    Hi,
    
    


    I've gone through some trouble to also dynamically load
    style information for the 'virtual' document that is being
    displayed. Here is some code that might help others too, in
    doing so.
    Maybe this is not the best COM code in existence, but
    it's working fine for me!

    Note that m_browser is a variable of type CWebBrowser2;
    thus a web browser control in a dialog.

    <CODE>
    HRESULT hr;

    // Get the browser
    IWebBrowser2* pBrowserApp;
    LPUNKNOWN lpUnk = m_browser.GetControlUnknown();
    hr = lpUnk->QueryInterface(IID_IWebBrowser2, (void**)&pBrowserApp);
    if(FAILED(hr)) return;

    // Get the browser contents
    LPDISPATCH lpDispatch;
    hr = pBrowserApp->get_Document(&lpDispatch);
    if(FAILED(hr)) return;
    if(!lpDispatch) return;

    // Get the html document
    IHTMLDocument3* pHtmlDoc;
    hr = lpDispatch->QueryInterface(IID_IHTMLDocument2, (void**)&pHtmlDoc);
    if(FAILED(hr)) return;

    // Get the body element
    IHTMLElement *pBodyElement;
    hr = pHtmlDoc->get_documentElement(&pBodyElement);
    if(FAILED(hr)) return;

    // Put content to body element
    CString c = "body {background: yellow;}"; // etcetera
    CComBSTR body( c );
    pBodyElement->put_innerHTML(body);
    </CODE>

    Good luck with it! It works here just fine, but took me
    three nights to get... so please re-use it ;-)

    Yours,


    Sander

    Reply
  • How to put "FrameSet" tag ?

    Posted by Legacy on 09/06/2002 12:00am

    Originally posted by: SA

    I put "<frameset>" tag to MSHTML.
    I tried,,,

    1.put_body
    2.IHTMLDocument2::write

    But "FrameSet" tag didn't insert.

    #1. "FrameSet" Tag wasn't inserted.
    #2. "FrameSet" Tag was inserted,But Page is blank.

    I think hardly.I ask to many people.
    But The problem does resolve.

    Please tell me & help !!!!

    Reply
  • cool stuff but still show exception warning... anyone has a clue

    Posted by Legacy on 07/12/2002 12:00am

    Originally posted by: Eric

    Thanks for sharing. This is what I'm looking for.

    Anyway, when I run in debug mode, I see a warning like this.

    Warning: constructing COleException, scode = DISP_E_MEMBERNOTFOUND ($80020003).
    First-chance exception in MoreHtmlViewDemo.exe (KERNEL32.DLL): 0xE06D7363: Microsoft C++ Exception.

    Anyone has a clue why and is there a way to fix it.

    Thanks in advance.

    Eric

    Reply
  • Loading, Please Wait ...

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Download the Information Governance Survey Benchmark Report to gain insights that can help you further establish business value in your Records and Information Management (RIM) program and across your entire organization. Discover how your peers in the industry are dealing with this evolving information lifecycle management environment and uncover key insights such as: 87% of organizations surveyed have a RIM program in place 8% measure compliance 64% cannot get employees to "let go" of information for …

  • Live Event Date: May 6, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT While you likely have very good reasons for remaining on WinXP after end of support -- an estimated 20-30% of worldwide devices still are -- the bottom line is your security risk is now significant. In the absence of security patches, attackers will certainly turn their attention to this new opportunity. Join Lumension Vice President Paul Zimski in this one-hour webcast to discuss risk and, more importantly, 5 pragmatic risk mitigation techniques …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds