Usually, I use: ShellExecute(0, 'OPEN', PChar(edtURL.Text), '', '', SW_SHOWNORMAL);
How can I have the same behaviour (opening a link in the default browser), on all platforms (Windows and OSX)?
Regarding the answer of mjn, I have written the following unit. I have successfully tested it on Windows but I don't have an OSX to test it on this platform. If someone can confirm it works, I'd appreciate.
unit fOpen;
interface
uses
{$IFDEF MSWINDOWS}
Winapi.ShellAPI, Winapi.Windows;
{$ENDIF MSWINDOWS}
{$IFDEF POSIX}
Posix.Stdlib;
{$ENDIF POSIX}
type
TMisc = class
class procedure Open(sCommand: string);
end;
implementation
class procedure TMisc.Open(sCommand: string);
begin
{$IFDEF MSWINDOWS}
ShellExecute(0, 'OPEN', PChar(sCommand), '', '', SW_SHOWNORMAL);
{$ENDIF MSWINDOWS}
{$IFDEF POSIX}
_system(PAnsiChar('open ' + AnsiString(sCommand)));
{$ENDIF POSIX}
end;
end.
and I call it like this:
TMisc.Open('https://stackoverflow.com/questions/7443264/how-to-open-an-url-with-the-default-browser-with-firemonkey-cross-platform-applic');
In the FireMonkey discussion forum I found this code for a question about NSWorkspace.URLForApplicationToOpenURL:
uses
Posix.Stdlib;
....
_system(PAnsiChar('open ' + ACommand));
(not tested by me)
Update: Posix is not available on Windows so it is not possible to write a solution which uses the same OS calls on all platforms. I suggest to move such code in a central 'XPlatform' unit which has some IFDEF POSIX etc.
For all platforms (Windows, macOs, iOS and Android) you can use the unit I wrote for my blog
unit u_urlOpen;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes,
System.Variants,
{$IF Defined(IOS)}
macapi.helpers, iOSapi.Foundation, FMX.helpers.iOS;
{$ELSEIF Defined(ANDROID)}
Androidapi.JNI.GraphicsContentViewText,
Androidapi.JNI.Net,
Androidapi.JNI.App,
Androidapi.helpers;
{$ELSEIF Defined(MACOS)}
Posix.Stdlib;
{$ELSEIF Defined(MSWINDOWS)}
Winapi.ShellAPI, Winapi.Windows;
{$ENDIF}
type
tUrlOpen = class
class procedure Open(URL: string);
end;
implementation
class procedure tUrlOpen.Open(URL: string);
{$IF Defined(ANDROID)}
var
Intent: JIntent;
{$ENDIF}
begin
{$IF Defined(ANDROID)}
Intent := TJIntent.Create;
Intent.setAction(TJIntent.JavaClass.ACTION_VIEW);
Intent.setData(StrToJURI(URL));
tandroidhelper.Activity.startActivity(Intent);
// SharedActivity.startActivity(Intent);
{$ELSEIF Defined(MSWINDOWS)}
ShellExecute(0, 'OPEN', PWideChar(URL), nil, nil, SW_SHOWNORMAL);
{$ELSEIF Defined(IOS)}
SharedApplication.OpenURL(StrToNSUrl(URL));
{$ELSEIF Defined(MACOS)}
_system(PAnsiChar('open ' + AnsiString(URL)));
{$ENDIF}
end;
end.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With