TMS FNC WebBrowser Event Completion

I am using a TMSFNCWebBrowser to download JSON for processing. I have everything working but I had to add sleep commands since I am unaware of another way to get the program to work correctly.

I navigate to the URL and wait for a flag to be set in the OnNavigateComplete event. I am not aware of a method to determine if the document has fully been downloaded so I ProcessMesages and sleep for two seconds.

I then extract the JSON and decode it. I have to wait for the ExecuteJavaScript to complete. I could probably use a flag and counter for this but am hoping there is a better approach. I then wait another second before continuing.

These steps work well but I have at least a 4.1 seconds delay each time I download another page of JSON.

How can I detect when the document download has been completed?

How can I detect when the ExecuteJavaScript is done?

I have tried leaving the sleep statements out but I don't get then I get a partial JSON document.

Here is the code:
Tries := 0;
f_NavigateComplete := False;
WB.Navigate(Url);
Application.ProcessMessages;
while (not f_NavigateComplete) and (Tries <= 100) do
begin
Tries := Tries+1;
Sleep(100);
Application.ProcessMessages;
end;
if f_NavigateComplete then
begin
Application.ProcessMessages;
Sleep(2000);
Application.ProcessMessages;
WB.ExecuteJavaScript('document.body.outerHTML',
procedure(const AValue: string)
var
S: String;
LJSONValue: TJSONValue;
begin
LJSONValue:= TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes(AValue),0);
S := LJSONValue.ToString;
S := StringReplace(S,'"','"',[rfReplaceAll]);
S := StringReplace(S,'\','',[rfReplaceAll]);
S := StringReplace(S,'/','',[rfReplaceAll]);
ContentMemo.Text := S;
end);
Sleep(1000);
end
else
ContentMemo.Text := '';
Application.ProcessMessages;
Sleep(1000);
Application.ProcessMessages;

That is correct. The OnDocumentComplete event is not triggered. This event is used for communicating with a TMS WEB Core application, and the TTMSFNCWebCoreClientBrowser. In a normal application, this event is currently not supported. We’ll see if we can add support for this event. For the JavaScript, you’ll need to write your own JavaScript function, that returns a value. For example:

WB.ExecuteJavaScript('function getBody(){return document.body.outerHTML};getBody();',BodyToText); // Sets f_Text using BodyToText