Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to start default browser with a URL(with spaces and #) for a local file? Delphi

I want to open a local HTML file in the default browser.

For example: Default Browser is Mozilla Firefox.

The file to be opened: C:\My Custom Path\New Folder\AFile.htm

Please note the path has spaces. Depending on conditions I want to append an Id at the end of the URL.

Final URL is C:\My Custom Path\New Folder\AFile.htm#12345

If I open the browser manually, and paste the URL "C:\My Custom Path\New Folder\AFile.htm#12345".

It works fine. Unable to find the best way to do this through code.

like image 944
ThatGuy Avatar asked Feb 06 '23 13:02

ThatGuy


2 Answers

ShellExecute/Ex() won't work directly using "open" verb with the anchor (#) in the URL. even if you use file:// protocol the anchor will be omitted.

The best way is to get the path for the default browser, you can use FindExecutable, and then execute it and pass the URL as a parameter.

uses
  ShellAPI;

procedure TForm1.Button1Click(Sender: TObject);
var
  Res: HINST;
  Buffer: array[0..MAX_PATH] of Char;
  SEInfo: TShellExecuteInfo;
  HtmlFile, Anchor: string;
begin
  HtmlFile := 'd:\1 - Copy.html';
  Anchor := '#123';

  FillChar(Buffer, SizeOf(Buffer), 0);
  Res := FindExecutable(PChar(HtmlFile), nil, Buffer);
  if Res <= 32 then
    raise Exception.Create(SysErrorMessage(Res));

  FillChar(SEInfo, SizeOf(SEInfo), 0);
  SEInfo.cbSize := SizeOf(SEInfo);
  with SEInfo do
  begin        
    lpFile := PChar(string(Buffer));
    lpParameters := PChar(Format('"file:///%s"', [HtmlFile + Anchor]));
    nShow := SW_SHOWNORMAL;
    fMask := SEE_MASK_FLAG_NO_UI; // Do not display an error message box if an error occurs.
  end;
  if not ShellExecuteEx(@SEInfo) then
    RaiseLastOSError;
end;

EDIT: Looks like the file:/// URI scheme is important in cases where the URL includes query string parameters (e.g file.html?param=foo#bar) or else the ? is escaped to %3F (tested in Chrome)

like image 161
kobik Avatar answered Feb 08 '23 03:02

kobik


Unfortunately you can't do it only with ShellExecute. But there is some hack.

For example you want to open url like this:

C:\Users\User\Desktop\Some sitename with spaces.htm with the anchor #myAnchor

To make ShellExecute open file:

vS := 'file:///C:\Users\User\Desktop\Some sitename with spaces.htm#MyAnchor';
ShellExecute(0, 'OPEN', PChar(vS), '', '', SW_SHOWNORMAL);

It's Important to use "file:///" in the beginning, but ShellExecute open this page without anchor.

To open with the anchor you can dynamically create html file with content like this:

<html>
<meta http-equiv=Refresh content="0; url=file:///C:\Users\User\Desktop\Some sitename with spaces.htm#MyAnchor">
<body></body>
</html>

And open this dynamic file with ShellExecute.

Hope it helps.

like image 41
Dimsa Avatar answered Feb 08 '23 02:02

Dimsa