6

是否可以将 Webbrowser(在 Delphi 中)中加载的整个文档保存为具有新值的普通 HTML 文件(我的意思是用户在 html 表单中输入的值这个文档)?下次使用应用程序时,我需要它来阅读这个包含所有值的 HTML 文档。

4

1 回答 1

7

当然这是可能的!

小型演示应用程序,创建一个新的 vcl 表单应用程序,在您的表单上放置 a TWebBrowser, aTButton和 aTMemo并使用此代码(不要忘记OnCreate为 Form 和OnClickButton 绑定)

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指出的那样,不会显示密码类型输入的值。不过,您仍然可以获得它们的价值:

将这两行添加到 Button1.Click 并更改 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]))
于 2012-12-20T10:53:52.190 回答