Page 1 of 1

How to inject HTML while in OnResourceRedirect?

Posted: Wed Dec 18, 2019 8:56 am
by JanDoggen
Background:

I have an OAuth login screen with a TCefWindowParent and a TChromium.
In the OnResourceRedirect event, I check if the URL we redirect to is the OAuth RedirectURI, and in that case I close my login screen by setting ModalResult to mrOK/mrCancel (depending on the parameters returned in NewURL), followed by the usual FormClose/ChromiumClose etc sequence.
This works fine, the form closes and returns with the ModalResult.

If I run this code in 'debugging mode' a memo becomes visible and I log event information to it.
In that case I do *not* set ModalResult so that the form stays open and the user can see the log. He can then click buttons to close the form, again doing the 'ModalResult thing'.
This also works.

Question:

While in the OnResourceRedirect, how can I inject some HTML code into TChromium to display a simple message like "You can now click the button to close this window"?

Code: Select all

   if not FDebugging then
   begin
      if (FAuthorizationCode = '') or (lState <> FState) then
         Self.ModalResult := mrCancel
      else
         Self.ModalResult := mrOK;
      PostMessage(Handle, WM_USER+1, 0, 0);
   end
   else
   begin 
      // HERE - How to inject HTML?
      //
      // Loading a file from disk does not work, I would not want that anyway:
      // NewURL := 'file:///' + StringReplace(fpath, '\', '/',[rfReplaceAll]);
   end;
Thanks in advance,
Jan

Re: How to inject HTML while in OnResourceRedirect?

Posted: Wed Dec 18, 2019 2:54 pm
by salvadordf
Hi,

The easiest way would be to do it outside that event.

Set a boolean variable to true inside OnResourceRedirect when you detect that you need to inject the HTML message and use TChromium.OnLoadEnd to execute some javascript code to inject the HTML message if the previous boolean variable was true.

The alternative way would be to use a filter but that's a lot more complicated.

Re: How to inject HTML while in OnResourceRedirect?

Posted: Fri Dec 20, 2019 11:00 am
by JanDoggen
That worked, thanks. For others:

Code: Select all

procedure TFrmTChromiumLogin.ChromiumLoadEnd(Sender: TObject; const browser: ICefBrowser; const frame: ICefFrame; httpStatusCode: Integer);
const
   lDiv = '<div style=\"position: absolute; top: 40%; left: 30%; margin: auto; width: auto; border: 3px solid green; padding: 10px;\">';
   lPar = '<p   style=\"color: green; font-weight: bold;\">';
   lText= 'Login geslaagd; u kunt dit venster nu sluiten met de OK knop';
var
   lJavaMsg: String;
begin
   if not FDebugging then Exit;
   if not FDebugMsgLogin then Exit;
   lJavaMsg := 'document.body.innerHTML = "%s %s %s %s"';
   lJavaMsg := Format(lJavaMsg,[lDiv, lPar, lText, '</p></div>']);
   MmoLog.Lines.Add(lJavaMsg);
   Chromium.Browser.MainFrame.ExecuteJavaScript(lJavaMsg, Chromium.Browser.MainFrame.GetURL, 0);
end;