Dynamically change WebBrowser Data flow content
Sometimes, due to the special needs of the software, we want Delphi to dynamically change the contents of the returned data in WebBrowser or EMBEDDEDWB, which requires returning all the original source code of the Web page, including the DOCTYPE HTML public declaration part of the Web page, Simply using MSHTML is not possible and requires a method of data flow.
The specific implementation method is as follows (requires uses Mshtml,activex):
Procedure Tform1.button1click (Sender:tobject);
Var
s:string;
Ms:tmemorystream;
Strstream:tstringstream;
Begin
Read into stream first, staged in Memo1
If not Assigned (embeddedwb1. Document) then Exit;
MS: = Tmemorystream.create;
(EMBEDDEDWB1. Document as IPersistStreamInit). Save (Tstreamadapter.create (MS), True);
Ms. Position: = 0;
Memo1.Lines.LoadFromStream (MS);
Ms. Free;
and remove the data output from the stream.
s: = Memo1.text;
Perform a replacement part of the code
S:=stringreplace (S, ' _blank ', ' _self ', [rfreplaceall,rfignorecase]);
Strstream:=tstringstream.create (s);
Try
strstream.position:=0;
(EMBEDDEDWB1. Document as IPersistStreamInit). Load (Tstreamadapter.create (Strstream));
Finally
Strstream.free;
End
End
Through the above conversion, can realize the non-destructive dynamic modification of Web page source code, to ensure the CSS format.
However, there is a problem, such as the original Web page URI is http://www.piaoyi.org, after the above data flow processing, the URL of the page becomes About:blank, which makes the Web page with a relative path to the file, such as Images/piaoyi.gif The path has gone wrong, which becomes about:blankimages/piaoyi.gif, which is obviously a path error. The workaround is to replace all relative paths with absolute paths. The way is to add the HTML code before the sentence: <base href= "http://www.piaoyi.org" >
In addition, there is a way to dynamically write the source code into WebBrowser or EMBEDDEDWB, as follows:
Procedure Tform11.button1click (Sender:tobject);
Var
V:olevariant;
Htmldocument:ihtmldocument2;
Begin
HTMLDocument: = embeddedwb1.document as IHTMLDocument2;
V: = Vararraycreate ([0, 0], varvariant);
V[0]: = ' Write html code here ';
Htmldocument.write (Psafearray (Tvardata (v). Varray));
Htmldocument.close;
End
Dynamically change WebBrowser Data flow content