FrankJensen
FrankJensen

Reputation: 11

delphi twebbrowser modify html before loaded

Is is possible to modify the html before it is loaded/executed in the browser?

To add functions to a web site out of my control I want to change a javascript from the original to my own.

E.g: in the html the browser load I would like to change:

<script src="/java.js" type="text/javascript"></script>  
to:
<script src="http://mysite/java.js" type="text/javascript"></script>  

I can not just load my own page as I need to login to the site for it to work and the site use cookies to check im logged in.


I load the modifyed code like this:

Var
  aStream     : TMemoryStream;

begin

if Assigned(WebBrowser1.Document) then 
begin       
aStream := TMemoryStream.Create;

try
     aStream.LoadFromFile(Root + 'main.htm');
     aStream.Seek(0, soFromBeginning);
     (WebBrowser1.Document as IPersistStreamInit).Load(TStreamAdapter.Create(aStream));
  finally
     aStream.Free;
     Timer1.Enabled := True;
  end;
  HTMLWindow2 := (WebBrowser1.Document as IHTMLDocument2).parentWindow;
end;

This used to work, but the site added a login and now the requests the javascript do get access denied. I have tried to navigate to the login and login before I load my own code, but I still get access denied.

Upvotes: 1

Views: 2643

Answers (3)

FrankJensen
FrankJensen

Reputation: 11

For now the problem are solved by adding another twebbrowser to the project. (On a new tab). This webbrowser handle the login and keep the required php session alive. (It is automatic keept alive as long as the window stay open). Now Im able to load my own modifyed code without access denied.

Thanks for all your help.

Upvotes: 0

stanleyxu2005
stanleyxu2005

Reputation: 8231

Here is the approach:

  1. Create a pluggable MIME filter (refer to IInternetProtocol) to monitor HTML document (mime type text/html) before it is rendered by TWebBrowser.
  2. Use regular expression to replace desired contents. In your case is to replace src="/java.js" with src="http://mysite/java.js".

Here is a code example. And I highly suggest you read these documents first.

  1. About Asynchronous Pluggable Protocols
  2. http://www.44342.com/webbrowser-control-f125-t489-p1.htm
  3. http://www.delphipraxis.net/60272-probleme-mit-plugable-protocol.html

Upvotes: 0

Remy Lebeau
Remy Lebeau

Reputation: 595329

In VCL, yes. You can download the HTML yourself and modify it as needed (you need to insert a <base href> tag specifying the original URL into the <head> if the HTML contains relative links). Then navigate the browser to about:blank, query its Document for the IPersistStreamInit interface, and call its load() method, passing it the modified HTML using the VCL's TStringStream and TStreamAdapter classes.

In FMX, I have no clue.

Upvotes: 1

Related Questions