Have you seen all of the free code samples available on our Marketplace?

NativeScript Angular

Web View

The WebView component is used to display web content within your application. You use the control by providing a src attribute that points at a URL or a local HTML file.

Image

Basic Web View

HTML

<GridLayout rows="75 * 50" sdkExampleTitle sdkToggleNavButton>
    <GridLayout row="0" rows="*" columns="50 * 50" class="form">
        <Button class="btn btn-primary btn-active icon" row="0" col="0" text="&#xea44;" (tap)="goBack()"></Button>
        <TextField #urlField row="0" col="1" hint="Enter URL" [text]="webViewSrc" returnKeyType="done" (returnPress)="submit(urlField.text)"
            autocorrect="false" verticalAlignment="center" class="input input-border m-t-0" autocapitalizationType="none"></TextField>
        <Button class="btn btn-primary btn-active icon" [isEnabled]="enabled" row="0" col="2" text="&#xea42;" (tap)="goForward()"></Button>
    </GridLayout>
    <WebView row="1" #myWebView [src]="webViewSrc"></WebView>
    <Label row="2" #labelResult></Label>
</GridLayout>

Add WebView src and handle loadFinishedEvent event

import { Component, OnInit, AfterViewInit, ViewChild, ElementRef } from "@angular/core";
import { WebView, LoadEventData } from "ui/web-view";
import { Page } from "ui/page";
import { TextField } from "ui/text-field";
import { Label } from "ui/label";

@Component({
    moduleId: module.id,
    templateUrl: "./basic-web-view.component.html",
    styleUrls: ["./style.css"]
})
export class BasicWebViewComponent implements AfterViewInit {
    public webViewSrc: string = "https://docs.nativescript.org/";
    public enabled: boolean = false;
    @ViewChild("myWebView") webViewRef: ElementRef;
    @ViewChild("urlField") urlFieldRef: ElementRef;
    @ViewChild("labelResult") labelResultRef: ElementRef;

    ngAfterViewInit() {
        let webview: WebView = this.webViewRef.nativeElement;
        let label: Label = this.labelResultRef.nativeElement;
        label.text = "WebView is still loading...";

        webview.on(WebView.loadFinishedEvent, function (args: LoadEventData) {
            let message;
            if (!args.error) {
                message = "WebView finished loading of " + args.url;
            } else {
                message = "Error loading " + args.url + ": " + args.error;
            }

            label.text = message;
            console.log("WebView message - " + message);
        });
    }

    goBack() {
        let webview: WebView = this.webViewRef.nativeElement;
        if (webview.canGoBack) {
            webview.goBack();
            this.enabled = true;
        }
    }
    goForward() {
        let webview: WebView = this.webViewRef.nativeElement;
        if (webview.canGoForward) {
            webview.goForward();
        } else {
            this.enabled = false;
        }
    }
    submit(args: string) {
        let textField: TextField = this.urlFieldRef.nativeElement;
        this.enabled = false;
        if (args.substring(0, 4) === "http") {
            this.webViewSrc = args;
            textField.dismissSoftInput();
        } else {
            alert("Please, add `http://` or `https://` in front of the URL string");
        }
    }
}

CSS

.icon{
    font-family: 'icomoon';
    vertical-align: center;
    margin: 6;
}

/*WebView {
    border-color: lightgray; 
    border-width: 0.5;
}*/

Improve this document

Demo Source


Events

The example shows the how to use the events supported by the WebView component and its reload method.

<GridLayout rows="50 50 50 *" columns="* *">
    <Button row="0" col="0" text="Load first url" (tap)="loadFirst()" ></Button>
    <Button row="0" col="1" text="Load second url" (tap)="loadSecond()" ></Button>
    <Button row="1" col="0" colSpan="2" text="Reload page" (tap)="onReload()" ></Button>
    <Label row="2" col="0" colSpan="2" [text]="'Url: ' + webViewSrc" textWrap="true" class="p-12" ></Label>

    <WebView #webview row="3" col="0" colSpan="2" (loadStarted)="onLoadStarted($event)" (loadFinished)="onLoadFinished($event)" [src]="webViewSrc" ></WebView>
    <GridLayout class="indicator" visibility="{{ isItemVisible ? 'visible' : 'collapsed' }}" row="0" col="0" rowSpan="4" colSpan="2">
            <ActivityIndicator width="100" height="100" busy="true"></ActivityIndicator>
    </GridLayout>
</GridLayout>
import { Component, ViewChild, ElementRef } from "@angular/core";
import { WebView, LoadEventData } from "tns-core-modules/ui/web-view";

@Component({
    moduleId: module.id,
    templateUrl: "./web-view-events.component.html"
})
export class WebViewEventsComponent {
    public webViewSrc = "https://www.nativescript.org/";
    public isItemVisible = true;

    @ViewChild("webview") webViewElement: ElementRef;
    private firstUrl = "https://google.com/";
    private secondUrl = "https://www.nativescript.org/";

    public onLoadStarted(args: LoadEventData) {
        this.isItemVisible = true;
        let message;
        if (!args.error) {
            message = "WebView started loading of " + args.url;
        } else {
            message = "Error loading " + args.url + ": " + args.error;
        }
        console.log(message);

    }
    public onLoadFinished(args: LoadEventData) {
        let message;
        if (!args.error) {
            message = "WebView finished loading of " + args.url;
        } else {
            message = "Error loading " + args.url + ": " + args.error;
        }
        console.log(message);
    }

    public loadFirst() {
        this.webViewSrc = this.firstUrl;
    }

    public loadSecond() {
        this.webViewSrc = this.secondUrl;
    }

    public onReload() {
        const webview: WebView = <WebView> this.webViewElement.nativeElement;
        webview.reload();
    }

}

In the sample code, we set up event loadStarted and loadFinished events. Both events will be fired when we change the source for the WebView component(change the URL or load local HTML file). The loadStarted event will be executed when the WebView source start loading and loadFinished will be fired when the source is already loaded. The events will return info about the eventName, navigationType and url, which we are trying to load. If an error appears on some of the steps of source load, we will receive the corresponding error with the error property in loadStarted or loadFinished events.

In the provided sample, it is also demonstrated how to reload the currently loaded source via WebView's reload method.

Improve this document

Demo Source


Gestures

The code samples show, how we could use gestures in WebView for both platforms iOS and Android.

XML

<GridLayout rows="50 50 *">
    <Label row="0" #touchlabel [text]="touchResult" textWrap="true" ></Label>
    <Label row="1" #panlabel [text]="panResult" textWrap="true" ></Label>
    <WebView row="2" (loaded)="onWebViewLoaded($event)"  (touch)="webViewTouch($event)" (pan)="webViewPan($event)" [src]="webViewSrc" ></WebView>
</GridLayout>

JavaScript

import { Component, ViewChild, ElementRef } from "@angular/core";
import { isAndroid } from "tns-core-modules/platform";
import { Label } from "tns-core-modules/ui/label";

@Component({
    moduleId: module.id,
    templateUrl: "./web-view-gestures.component.html"
})
export class WebViewGesturesComponent {
    public webViewSrc = "<!DOCTYPE html><html><body><h1>My First Heading</h1><p>My first paragraph.</p></body></html>";
    public touchResult = "Touch: x: _ y: _";
    public panResult = "Pan: deltaX: _ deltaY: _";

    public onWebViewLoaded(webargs) {
        const webview = webargs.object;
        if (isAndroid) {
            webview.android.getSettings().setDisplayZoomControls(false);
        }
    }

    public webViewTouch(args) {
        this.touchResult = `Touch: x: ${args.getX().toFixed(3)} y: ${args.getY().toFixed(3)}`;
        console.log(`Touch: x: ${args.getX().toFixed(3)} y: ${args.getY().toFixed(3)}`);
    }

    public webViewPan(args) {
        this.panResult = `Pan: deltaX: ${args.deltaX.toFixed(3)} deltaY: ${args.deltaY.toFixed(3)}`;
        console.log(`Pan: deltaX: ${args.deltaX.toFixed(3)} deltaY: ${args.deltaY.toFixed(3)}`);
    }
}

Note: to be able to use gestures in WebView component on Android, we should first disabled the zoom control. To do that we could access the android property and with the help of setDisplayZoomControls to set this control to false.

Improve this document

Demo Source


Web View Html

HTML

<GridLayout rows="100 *" columns="*">
    <WebView row="0" col="0" [src]="firstWebViewSRC"></WebView>
    <WebView row="1" col="0" [src]="secondWebViewSRC"></WebView>
</GridLayout>

Add WebView src from local file

import { Component } from "@angular/core";

@Component({
    moduleId: module.id,
    templateUrl: "./web-view-html.component.html",
})
export class WebViewHtmlComponent {
    public firstWebViewSRC = '<!DOCTYPE html><html><head><title>MyTitle</title><meta charset="utf-8" /></head><body><span style="color:#0099CC; text-align: center;">First WebView</span></body></html>';
    public secondWebViewSRC = "~/ng-ui-widgets-category/web-view/web-view-html/test.html";
}

Improve this document

Demo Source


API Reference for the WebView Class

Native Component

Android iOS
android.webkit.WebView UIWebView