With my Telerik NativeScript adventures pressing on, I ran into an obstacle that took me quite some time to figure out. I wanted to launch a URL from within my application in the iOS and Android system web browser. It wasn’t obvious in the documentation at the time of writing this, but after a lot of trial and error, I figured it out.
In this guide we’re going to look at launching URLs in a web browser from our NativeScript application.
Let’s start by creating a fresh NativeScript project for Android and iOS:
tns create ExampleProject
cd ExampleProject
tns platform add ios
tns platform add android
It is important to note that if you’re not using a Mac, you cannot add and build for the iOS platform.
With your new NativeScript project, crack open app/main-page.xml and change it to contain the following XML:
<Page loaded="pageLoaded">
<StackLayout>
<Button text="Launch URL" tap="launch" />
</StackLayout>
</Page>
We just have a view with a Button
element that executes a launch
function when we tap it. We’re going to define the launch
function in a moment.
Go ahead and open your project’s app/main-page.js file because this is where all the magic is going to happen. For simplicity, we are going to wipe out the entire file and replace it with the following:
var utilityModule = require("utils/utils");
function pageLoaded(args) {
var page = args.object;
page.bindingContext = { };
}
exports.pageLoaded = pageLoaded;
exports.launch = function() {
utilityModule.openUrl("https://www.thepolyglotdeveloper.com");
}
Let’s break down the two important lines in this file:
var utilityModule = require("utils/utils");
This allows us to gain access to a bunch of NativeScript utility functions. The utility function we are after in particular is the openUrl
function as demonstrated in the launch
tap event. Whatever string value you pass to it will be launched in the web browser.
We just saw how to open a URL in the system web browser for Android and iOS using NativeScript. In reality it wasn’t too difficult, just difficult to determine from the current documentation. If you were keeping up with my other tutorials, you’ll know I’ve demonstrated launching URLs from an Ionic Framework application as well.
A video version of this article can be seen below.