Launching URIs in a Windows Store app
During the writing of a Windows Store app, we got a requirement to launch a web page from the app. Launching a web page means opening a browser with a given URI. So how can you accomplish that? The answer is very simple and is explained in this post.
The Windows.System.Launcher Namespace
In Windows Store apps you can use the WinRT Windows.System.Launcher namespace to launch web pages or files. The namespace includes the following API functions:
- launchUriAsync – receives a Windows.Foundation.Uri and open it in the app associated with the URI scheme (in most cases a browser).
- launchFileAsync – receives a IStorageFile and start it using the default app that is associated with the file type.
The following example shows how to launch a URI:
Both of the functions can receive an additional LauncherOptions parameter. The LauncherOptions can help to configure the launch with options like content type or display application picker. Here is a simple example that will open the application picker:
Launching a URI
Formatting a URI String
In the example I’m going to use a string format function. The function receives string arguments and replace placeholders, represented with curly brackets and an argument index number, with the associated arguments. The format function is added to the string prototype and it is very useful in other situations:
Launching a formatted URI
In the example I’m using the following URI:
I could have used string concatenation to create the URI but in real world scenarios you are probably going to format a more sophisticated URI so I decided to use the format function instead.
Here is the code to launch a search in Google:
The Full Example
Here is the entire code for a launchManager:
Now you can use the Launcher namespace like in the following example:
In order to launch files or web pages you can use the Windows.System.Launcher namespace. In the post I showed how to launch an app associated with a given URI scheme.