【发布时间】:2017-02-02 13:08:52
【问题描述】:
我在 DesignMode (Doc.DesignMode := 'On') 中使用 TWebBrowser 来编写 HTML 文档。 TWebBrowser 中没有加载文档(磁盘上的 HTML 文件)。我直接在 TWebBrowser 中从零开始创建文档。 html 代码将从 TWebBrowser 中提取并保存为 c:/MyProjects/SomeHtmlName.html。
问题是如果我插入的图片有相对路径,它就不会显示它们。
更准确地说,如果我将此代码粘贴到 WebBrowser 中,它将立即显示图像:
<IMG src="file:///c:/MyProjects/resources/R.PNG">
但是,如果我输入:
<IMG border=0 src="resources\R.PNG">
<IMG border=0 src="resources/R.PNG"> <---- preferred so it will work on Linux
它将显示一个图像占位符而不是实际图像。
我需要相对路径,因此如果我更改根路径或将其上传到 FTP 上,网站仍然可以工作。
procedure TForm1.Button1Click(Sender: TObject);
begin
LoadDummyPage;
SetHtmlCode('<img src="resources/test_img.PNG">');
Memo1.Text:= GetHtmlCode;
end;
function TForm1.LoadDummyPage: Boolean;
const FileName: string= 'c:\MyProject\_ONLINE WEB SITE\dummy.html';
begin
if not Assigned(wbBrowser.Document)
then wbBrowser.Navigate('about:blank');
Result := FileExists(FileName);
if Result
then wbBrowser.Navigate('file://' + FileName)
else Caption:= 'file not found';
end;
procedure TForm1.SetHtmlCode(const HTMLCode: string);
var
Doc: Variant;
begin
if not Assigned(wbBrowser.Document)
then wbBrowser.Navigate('about:blank');
Doc := wbBrowser.Document;
Doc.Write(HTMLCode);
Doc.Close;
Doc.DesignMode := 'On';
WHILE wbBrowser.ReadyState < READYSTATE_INTERACTIVE
DO Application.ProcessMessages;
Doc.body.style.fontFamily := 'Arial';
Doc.Close;
end;
function TForm1.GetHtmlCode: string; { Get the HTML code from the browser }
var
Doc: IHTMLDocument2;
BodyElement: IHTMLElement;
begin
if Assigned(wbBrowser.Document) and (wbBrowser.Document.QueryInterface(IHTMLDocument2, Doc) = S_OK) then
begin
BodyElement := Doc.body;
if Assigned(BodyElement) then
Result := BodyElement.innerHTML;
end;
if Result > ''
then Result := StringReplace(Result, '="about:', '="', [rfReplaceAll, rfIgnoreCase]); { Fix the 'How stop TWebBrowser from adding 'file:///' in front of my links' bug }
end;
【问题讨论】:
-
如果可执行文件的当前工作目录是c:/MyProjects/,是否有效?
-
我可以使用的“hack”是对 HTML 进行后处理并删除“file:///c:/MyProjects/”
-
@mjn42 - 不。可能是因为图像位于“资源”文件夹中?另外,我认为 TWebBrowser 的“根”文件夹是 Internet Explorer 的默认根文件夹(不管它是什么),而不是应用程序的文件夹。
-
@DarkPresidentOfAmerica,你错了。您需要预加载一个 HTML“模板”字符串/流,包括设置所需路径(带有斜杠)的 BASE 标记,例如
"file:///c:/MyProjects/"。并切换到编辑模式,您的图像 src 应该是相对的,例如"resources/R.PNG"。您最终提取的 HTML 后编辑应该是body.innerHTML。用没有 BASE 标记的有效 HTML/Body 包装它并保存到磁盘。
标签: html delphi twebbrowser