Search code examples
delphiwebbrowser-controltwebbrowser

TWebBrowesr Insert HTML code into body after navigate a local file


I use TWebBrowser in Delphi 10.x, I want to navigate to local file like index.html that will load some html/js/css, it is working and loaded successfully. Now I wanted to add to the body some html text, but it is not working, nothing happened (without raising errors).

//Navigate to local file
   WebBrowser.Navigate(f);
//Writing a string to body
   with WebBrowser.Document as IHTMLDocument2 do
   begin
      WebBody := body;
      WebBody.insertAdjacentHTML('BeforeEnd', MyHTML);
   end;

If i do not Navigate to a local file but write a whole HTML as string to it,

    Navigate('about:blank', '', '', '', 'X-UA-Compatible: IE=edge,chrome=1');
   ...//write a initial html like above

then adding text by WebBody.insertAdjacentHTML, it is work fine.

How can I navigate local file then add some text to body (let assume it is chat app).


Solution

  • I found the solution depend on @whosrdaddy comment above but not using OnDocumentComplete.

    I should wait browser to complete the navigating/processing it

    procedure WaitComplete; 
    begin
        with WebBrowser do
          while Busy or (ReadyState <> READYSTATE_COMPLETE) do
          begin
            Vcl.Forms.Application.ProcessMessages;
          end;
    end;
    
    WebBrowser.Navigate(f);
    WaitComplete;