如何保存 TWebBrowser 的内容,包括用户输入的表单值? [英] How do I save the contents of TWebBrowser, including user-entered form values?
问题描述
是否可以将加载在 Webbrowser(在 Delphi 中)中的整个文档保存为具有新值的普通 HTML 文件(我的意思是用户在该文档的 html 表单中输入的值)?下次使用应用程序时,我需要它来阅读这个包含所有值的 HTML 文档.
is it possible to save entire document loaded in Webbrowser (in Delphi) as a ordinary HTML file with new values (I mean values entered by user in html's forms this document)? I need this for reading this HTML document with all values next time when application will be used.
推荐答案
当然可以!
小型演示应用,制作一个新的 vcl 表单应用程序,在表单上放置一个 TWebBrowser
、一个 TButton
和一个 TMemo
并使用它代码(不要忘记为表单绑定 OnCreate
和为按钮绑定 OnClick
)
Small demo App, make a new vcl forms application, drop a TWebBrowser
, a TButton
and a TMemo
on your form and use this code (don't forget to bind OnCreate
for the Form and OnClick
for the Button)
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, OleCtrls, SHDocVw, StdCtrls,mshtml, ActiveX;
type
TForm1 = class(TForm)
WebBrowser1: TWebBrowser;
Button1: TButton;
Memo1: TMemo;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
//code snagged from about.com
procedure WBLoadHTML(WebBrowser: TWebBrowser; HTMLCode: string) ;
var
sl: TStringList;
ms: TMemoryStream;
begin
WebBrowser.Navigate('about:blank') ;
while WebBrowser.ReadyState < READYSTATE_INTERACTIVE do
Application.ProcessMessages;
if Assigned(WebBrowser.Document) then
begin
sl := TStringList.Create;
try
ms := TMemoryStream.Create;
try
sl.Text := HTMLCode;
sl.SaveToStream(ms) ;
ms.Seek(0, 0) ;
(WebBrowser.Document as IPersistStreamInit).Load(TStreamAdapter.Create(ms)) ;
finally
ms.Free;
end;
finally
sl.Free;
end;
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
Doc : IHtmlDocument2;
begin
Doc := WebBrowser1.Document as IHtmlDocument2;
Memo1.Lines.Text := Doc.body.innerHTML;
end;
procedure TForm1.FormCreate(Sender: TObject);
var
Html : String;
begin
Html := 'change value of input and press Button1 to changed DOM<br/><input id="myinput" type="text" value="orgval"></input>';
WBLoadHTML(WebBrowser1, Html);
end;
end.
输出:
编辑
正如mjn所指出的,password类型输入的值不会显示.不过,您仍然可以获得它们的价值:
As mjn pointed out, the values of password type inputs will not be shown. You can still can get their value though:
将这两行添加到 Button1.Click 并更改 html
add these 2 lines to Button1.Click and change html
创建时:
Html := 'change value of input and press Button1 to changed DOM<br/><input id="myinput" type="password" value="orgval"></input>';
点击:
El := (Doc as IHtmlDocument3).getElementById('myinput') as IHtmlInputElement;
Memo1.Lines.Add(Format('value of password field = %s', [El.value]))
这篇关于如何保存 TWebBrowser 的内容,包括用户输入的表单值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!