iframe in Ionic

Learn How to embed an iframe in ionic apps

Jump to a specific topic

I was recently struggling at how to embed an iframe in the ionic app. And when I got the solution, I thought I must help other aspiring developers too. So, today our main focus will be on making an ionic application in which I will show you how to embed URLs in an ionic app using iframe and domsanitizer.

Prerequisites

Before starting, let’s make sure we have everything we need set up on our computer.

  • Node.js
  • npm
  • Ionic
  • Cordova

Getting Started

We will go in a step-by-step manner to explore how to embed URLs in the ionic app.
Problem Statement – Take URL as user input and embed the given URL using iframe in the ionic app.

STEPS:

  1. Creating ionic app
  2. Taking URL as input from the user
  3. Adding router and using iframe
  4. Installing the DomSanitizer plugin
  5. Adding platforms in the ionic app
  6. Allowing navigation on iOS

Ionic App Creation

In short, the steps you need to take here are

  • Create an ionic app using the start command

For now to proceed with ionic app development first we will create an ionic blank app as shown below.

ionic start website_fetcher blank
sudo ionic start app_name blank
Screenshot for command output

On running the above command you will see a new project directory website_fetcher, change the working directory 👉🏻

cd app_name

You can run ionic serve to see the ionic application running in your browser

sudo ionic serve

When you run the above command you will see logs like below in your terminal. Then at the end of logs, you will see a link like a localhost:port-number, we need to hit that link in the browser to see our app running.

sudo ionic serve

So let’s start with building our ionic application which basically involves two steps:

  1. First to take URL as input from the user
  2. To use that URL and fetch the website

Taking URL as input (Front-End)

Editing Home Page(HTML)

So ,for that we will head over to src >> app >> home >>home.html

  • We will create an input box in which we can enter the URL : As, in the basic HTML we use <label> to associate a text label with a form <input> field. Similarly, here we will use “<ion-label”. And I am sure you do know what is <input> tag in HTML…well if not don’t worry I will tell you. The HTML <inputelement is used to create interactive controls for web-based forms in order to accept data from the user. And as we are using ionic so ionic has it’s own tags i.e <ion-label> and <ion-input> so let’s use them.
  • We will create a button to upload the given URL : As you must be familiar with HTML tags and we use <button> in HTML…in the same way we will use <ion-button> over here as buttons are simple components in Ionic. They can consist of text and icons and be enhanced by a wide range of attributes.
<ion-header [translucent]="true">
  <ion-toolbar>
    <ion-title>
    Website Fetcher
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content [fullscreen]="true">
  <ion-item>
    <ion-label color="primary" stacked>Enter URL</ion-label>
    <ion-input type="nameofurl" placeholder="Please enter url" [(ngModel)]="nameofurl" ></ion-input>
  </ion-item>
 
  <ion-button expand="block" (click)="uploadURL()" >Upload URL</ion-button>

</ion-content>

Adding Routers (Back-End)

Editing Home Page (Typescript)

So ,for that we will follow the path: src >> app >> home >>home.ts
In the home.ts file, we can add functions and variables which we are using in the HTML file.

Adding two variables:

  • Name of the URL (for binding with the input box)
  • URL
export class HomePage {
  public nameofurl:string;
  public url:string;
  constructor() {}
}

Adding function uploadURL() which will work on click of the button specified in html.

uploadURL(){
    this.url=this.nameofurl;
    localStorage.setItem('url', this.url);
    this.router.navigateByUrl('/result');
  }

Now, we will add router and the code given below will go in the constructor of our typescript file.

Routing is an important part of any mobile application /web application and here for the ionic application, we use routers as router helps in navigating from one view to another view.

private router: Router

Finally, the home.ts file will look like:

import { Component } from '@angular/core';
import { Router } from '@angular/router';
@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {
  public nameofurl:string;
  public url:string;
  constructor(private router: Router) {}

  uploadURL(){
    this.url=this.nameofurl;
    localStorage.setItem('url', this.url);
    this.router.navigateByUrl('/result');
  }
}

Add a new Page (Result Page)

As you can see I have navigated it to result so we need to add a page named as result hence adding the page using below command.

sudo ionic generate page result
//Output- Generated page!

Adding iframe (Front-End)

Editing Result Page(HTML)

In this page we will use iframe in our ionic app to show the url given by user and a button to go back

iframe(Inline frame) allows us to include another documents into our ionic application hence here we will use iframe in which we will give URL of a website and it will get embedded in it.

<ion-header>
  <ion-toolbar>
    <ion-title>Loaded URL</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content [fullscreen]="true">
  <ion-button expand="block" (click)="goback()" >Go Back</ion-button>
  <iframe class= 'webPage' name= "eventsPage" [src]="openURL()" allowfullscreen>
  </iframe>
</ion-content>

Adding DomSanitizer

Editing Result Page(Typescript)

First we will add router in our ts file and we will complete going back functionality.

import { Router } from '@angular/router';

As done in home.ts file we follow same for result.ts and we will add router in constructor of result.ts file.

private router: Router

Adding function goback() to redirect user back to home page from the result page

goback(){
this.router.navigateByUrl('/home');
}

Adding function openURL() to open the URL given by user in iframe

openURL(){
    return localStorage.getItem("url");
}

Awesome, let’s run it and see if it works. But…
URL doesn’t get loaded into the iframe as we would have expected.

The reason for this is that a url to be loaded into an iframe isn’t be seen as safe by Angular and therefore Angular won’t load it.

To circumvent this and to tell Angular that the URL is safe to be loaded, the URL has to be sanitized by the DomSanitizer. So, add the following imports to your home.ts file:

First let’s import DomSanitizer

import { DomSanitizer} from '@angular/platform-browser';

We are injecting the DomSanitizer service and we will execute the bypassSecurityTrustHtml method because as you know here we are dealing with HTML context to Bypass security and trust the given value to be safe HTML.

Note: If we will call these methods with untrusted user data will expose our ionic application to XSS security risks!!!

So, please be careful.

Also adding it in constructor of result.ts

public sanitizer: DomSanitizer

Now let’s get back to openURL() function and let’s change it

openURL(){
  
    return this.sanitizer.bypassSecurityTrustResourceUrl(localStorage.getItem("url"));
  
  }

So, our result.ts file should look like:

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { DomSanitizer} from '@angular/platform-browser';
@Component({
  selector: 'app-result',
  templateUrl: './result.page.html',
  styleUrls: ['./result.page.scss'],
})
export class ResultPage implements OnInit {

  constructor(private router: Router,public sanitizer: DomSanitizer) { }

  ngOnInit() {
  }
  goback(){
    this.router.navigateByUrl('/home');
  }
  openURL(){
    
    return this.sanitizer.bypassSecurityTrustResourceUrl(localStorage.getItem("url"));
  
  }
}

Let’s check the app now using ionic serve

iframe got loaded

Beautiful, as expected the iframe got loaded but couldn’t be seen in full screen for that we need to add some css to it…

So our result.scss file will look like below:

ion-content div.scroll{
    height: 90%; 
 }
 
 .webPage{
    width: 100%;
    height: 100%;
    background-color: transparent;
    padding: 1rem;
 }

On running the application again we will see following result in the browser.

Loaded Url in iframe

YAYY!!! IT IS WORKING!!!

Adding Platform

Let’s add ios as platform and try to run our application.

sudo ionic cordova platform add ios

Let’s build and run it on emulator

sudo ionic cordova emulate ios -c -l
App Screenshots

So you will see that even though you entered url and the url which was working fine in browser isn’t working for ios application so for that we need to allow navigation on iOS.

Allow navigation on iOS

So,there is one more thing we need to do in order to make this work on iOS, we need to allow navigation to the urls in our config.xml file by adding the below line:

<allow-navigation href="*"/>

Let’s run again and check in iOS.

Loaded URL in iframe (in phone)

Conclusion

Have a request or topic you want to see covered? Please comment below in the comments section.

See you in the next blog!

References

Learn How to embed an iframe in ionic apps
Share on facebook
Share on twitter
Share on linkedin
Share on whatsapp
Anshul Chhabra

Anshul Chhabra

I'm a full-stack software engineer with over 2.7 years of experience. I like to write blogs covering various topics varying from mobile app development to python basics or learning i have gathered by building products, to make life easier for every other aspiring developer like me.
If my content adds value to your life, do consider supporting me!

Anshul Chhabra

Anshul Chhabra

I'm a full-stack software engineer with over 2.7 years of experience. I like to write blogs covering various topics varying from mobile app development to python basics or learning i have gathered by building products, to make life easier for every other aspiring developer like me.
If my content adds value to your life, do consider supporting me!

Subscribe
Notify of
guest
3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Md Najmul Hoda

Thanks for sharing this article Anshul. Do you know how to show a pdf in iframe in android using ionic. I tried your example but it not work. Could you please help me. Thanks

Last edited 1 month ago by Md Najmul Hoda
Md Najmul Hoda

Thank you Anshul, appreciate your help. It worked on my capacitor project, but on cordova its giving clearText error which I tried to fix with some online help but could not. However I think, I will manage to fix that. Thank you again Anshul.

Last edited 1 month ago by Md Najmul Hoda
Share on facebook
Share on twitter
Share on linkedin
Share on whatsapp

Join the Club!

Get all the latest blog updates directly in your mailbox and stay ahead of the curve.

Yes, I'm IN!

Join and Stay ahead of the curve.