Opening webpage in default browser with double-quotes (") inside url
Asked Answered
V

1

8

When I try to open any site that has double-quotes (") inside the link , for ex. user.php?name="stackoverflow" it just cuts " or sometimes it redirects me to Google!? Used code:

ShellExecute(0, 'open', PChar('open'), PChar(URL), nil, SW_SHOW) ;
Viol answered 14/4, 2012 at 14:58 Comment(0)
S
19

You need use a fully qualified URL including the http:// and escape/encode the URL by replacing the double-quotes (") with %22.

Also you are passing wrong parameters.

See MSDN: Use ShellExecute to launch the default Web browser

Example:

procedure TForm1.Button1Click(Sender: TObject);
var
  URL: string;
begin
  URL := 'http://www.user.com/?name="stackoverflow"';
  URL := StringReplace(URL, '"', '%22', [rfReplaceAll]);
  ShellExecute(0, 'open', PChar(URL), nil, nil, SW_SHOWNORMAL);
end;

You should always encode the URL parameters, not only double-quotes. You can use Indy with TIdURI.URLEncode - IdURI unit.
You could also use HTTPEncode from the HTTPApp unit to encode each parameter in the URL.

Note that TIdURI.URLEncode will encode the ? and the & separators also. so I think it's a better idea to encode each parameter separately with HTTPEncode e.g:

URL := 'http://www.user.com/?param1=%s&param2=%s';
URL := Format(URL, [
  HTTPEncode('"stackoverflow.com"'),
  HTTPEncode('hello word!')]);
// output: http://www.user.com/?param1=%22stackoverflow.com%22&param2=hello+word!
Sammy answered 17/4, 2012 at 19:24 Comment(5)
+1, but it's much better to use Indy's URLEncode (forget which unit, and don't have D7 here to check), which will properly handle all values and not just quotes (like spaces, &, and so forth). It's in IdURI.pas in D2007 (Indy 9).Are
<g> Thanks Ken, I was just editing the answer with the remark about Indy URLEncode. I remember that there is another unit that does that. I am looking in the D7 source folder but cant find it... :/Sammy
@KenWhite, BTW TIdURI.URLEncode will encode the ? and the '&` separators also. so I think it's a better idea to encode each parameter separately with HTTPEncode.Sammy
Might be; I haven't used it for a while (not doing anything currently that needs it - mostly SFTP/PGP stuff, which doesn't). I think it might still resolve correctly, though; can't test it right now, though (and don't really need to know now, either <g>).Are
Please note that under Delphi 10.2 (Tokyo) this will execute nothing. However, the code will work if executed outside debugger!Tendentious

© 2022 - 2024 — McMap. All rights reserved.