Using iframe to create a page "browser" in Ionic2

Keywords: angular Android

Catalog

Preface

We will encounter such a requirement as loading a web page in Ionic2, such as loading an H5 page in Ionic2, the content of the page can be information details or activity details, etc. So in Ionic2, you need something like this to load H5 pages. There is WebView in Android native. So what's in Ionic2?

ionic-native

In Ionic2, the ionic-native package provides two cordova plug-ins, InAppBrowser and Themeable Browser, to open a "WebView" like window for loading pages.

Use of Themeable Browser

If you use the Themeable Browser plug-in to open a new window load page, the effect is as follows:

Use Themeable Browser for reference, an article I wrote< The Use of Themeable Browser Plug-in in Ionic 2: App Embedded Browser>.

Disadvantages of Themeable Browser

1. When using Themeable Browser, it is cumbersome to define the top title bar style, and it is not easy to define the de style consistent with the current APP theme.
2. The cordova plug-in can not be invoked when the browser is debugged. It needs real machine to run.
3. It's not easy to add some custom menu items to the title bar.

Loading pages using iframe imitation browser

In order to make this iframe more general and more like a "browser". Here, we define a Browser Page page in Ionic2. When we open the page, we need to pass browser configuration parameters, such as page title, page links visited, definition of sharing configuration, etc.
In this browser, a popover menu is defined. By default, it only has the functions of "refresh" (refresh page) and "close" (close current page).

browser.html

A "browser" page is defined here, which contains the progress bar displayed when loading the page (it can be said to be a pseudo-progress bar, without calculating the progress when actually accessing the page).

<ion-header no-shadow>
  <ion-navbar class="page-navbar">
    <ion-title>{{browser.title}}</ion-title>

    <ion-buttons end>
      <button ion-button icon-only (click)="presentPopover($event)">
        <ion-icon name="more"></ion-icon>
      </button>
    </ion-buttons>
  </ion-navbar>
</ion-header>

<ion-content class="content"> <!--scroll="true" overflow-scroll="true"-->
  <div class="progress" [hidden]="browser.isLoaded">
    <div class="progress-inner" id="progress"></div>
  </div>

    <iframe id="iframe" class="iframe"
            sandbox="allow-scripts allow-top-navigation allow-pointer-lock allow-same-origin allow-popups allow-forms"
            [src]="browser.secUrl"
            (load)="loaded()">
    </iframe>
</ion-content>
<panel-share [(isShow)]="shareConfig.isShow" [share]="browser.share"></panel-share>

Note: A panel-share component is defined to display sharing functions (e.g. Wechat Sharing, Friendship Sharing, QQ Sharing, etc.). Users can define their own sharing components when they click "Share" on the menu bar. Here's just a chestnut.

browser.scss

Define browser style and progress bar style.

page-browser {
  $progress-height: 0.2rem;
  //$progress-bg: #d43f3a;
  //$progress-bg: linear-gradient(-45deg, #333 100%, #324512 60%,rgba(255,255,255,0.5) 0%);
  //$progress-bg: linear-gradient(left, #5bd8ff, #ff0000);
  //$progress-bg: linear-gradient(-45deg, rgba(255,255,255,0.5)0%, #324512 60%,#333 100%);
  $progress-bg: #77b6ff;

  .scroll-content {
    overflow: hidden;
  }

  .content {
    height: 100%;
  }

  .progress{
    position: absolute;
    top: 0;
    right: 0;
    left: 0;
    height: $progress-height;
    background: #f5f5f5;
    z-index: 200;
  }

  .progress-inner{
    width: 0;
    background: $progress-bg;
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;

    box-shadow: 0 0 10px rgba(119,182,255,0.7);
    -webkit-transition: width 0.4s ease;
    transition: width 0.4s ease;
  }

  .iframe {
    width: 100%;
    height: 100%;
    border: none;
  }
}

browser.ts Defines Browser Functions

The main functions include displaying progress bars, refreshing pages and sharing callbacks when loading pages (the configuration parameters of sharing passed in when opening browser pages).

/**
 * Created by DreamBoy on 2016/11/21.
 */
import { Component } from '@angular/core';
import { NavController, NavParams, PopoverController } from 'ionic-angular';
import { DomSanitizer } from "@angular/platform-browser";
import { BrowserPopoverPage } from "./browser-popover";

@Component({
  selector: 'page-browser',
  templateUrl: 'browser.html'
})
export class BrowserPage {
  browser: any = {
    isLoaded: false, // Whether Web pages are loaded or not
    proObj: null, // Progress Bar Object
    progress: 0, // Progress Bar for Web Access
    secUrl: '', // Security link

    title: 'Loading',
    url: '',
    share: null // Whether it has a sharing function (passing a shared object) ShareModel Come over)
  };

  shareConfig: any = {
    isShow: false
  }; // Configuration of shared control

  constructor(public navCtrl: NavController,
              private params: NavParams,
              private sanitizer: DomSanitizer,
              private popoverCtrl: PopoverController) {
    let browser = this.params.get('browser');
    if(browser) {
      this.browser.title = browser.title;
      this.browser.url = browser.url;
      this.browser.secUrl = this.sanitizer.bypassSecurityTrustResourceUrl(browser.url);

      if(browser.share) {
        this.browser.share = browser.share;
      }

    } else {
      this.browser.secUrl = this.sanitizer.bypassSecurityTrustResourceUrl(this.browser.url);
    }
    this.reload();
  }

  ionViewDidLoad() {
    if(!this.browser.proObj) {
      this.browser.proObj = document.getElementById('progress');
    }
    this.onprogress();
  }

  // Generating Random Numbers
  private random(min: number, max: number): number {
    return Math.floor(Math.random() * (max - min + 1) + min);
  }

  // Page access progress
  private onprogress() {
    // Random time
    let timeout = this.random(10, 30);

    let timer = setTimeout(() => {
      if(this.browser.isLoaded) {
        this.browser.proObj.style.width = '100%';
        clearTimeout(timer);
        return;
      }

      // Stochastic progress
      this.browser.progress += this.random(1, 5);

      // Random progress should not exceed 90%,Lest the page has not been loaded, progress has been made. 100% 了
      if(this.browser.progress > 90){
        this.browser.progress = 90;
      }

      this.browser.proObj.style.width = this.browser.progress + '%';
      this.onprogress();
    }, timeout);
  }

  // IfiframeAfter successful page loading
  loaded() {
    this.browser.isLoaded = true;
  }

  // displayPopveroption
  presentPopover(myEvent) {
    let cb = {
      refresh: () => {
        this.reload();
      },
      close: () => {
        this.navCtrl.pop();
      },
      share: null
    };

    if(this.browser.share) {
      cb.share = () => {
        this.share();
      }
    }

    let popover = this.popoverCtrl.create(BrowserPopoverPage, {
      callback: cb
    });
    popover.present({
      ev: myEvent
    });
  }

  // Reload the page
  reload() {
    let title = this.browser.title;
    let url = this.browser.secUrl;
    this.browser.title = 'Loading';
    this.browser.secUrl = this.sanitizer.bypassSecurityTrustResourceUrl('');

    setTimeout(() => {
      this.browser.isLoaded = false;
      this.browser.progress = 0;
      if(!this.browser.proObj) {
        this.browser.proObj = document.getElementById('progress');
      }
      this.onprogress();
      this.browser.title = title;
      this.browser.secUrl = url;
    }, 10);
  }

  // Share pages (aspopoverCallback)
  share() {
    this.shareConfig.isShow = true;
    /*if(this.browser.share) {
      SocialSharing.share(this.browser.share.title, this.browser.share.content, '', this.browser.share.url).then(() => {

      }, (err) => {
        // Error!
        alert('Error: Sharing Failure! ' + err);
      });
    }*/
  }
}

browser-popover.ts menu item

Click on the corresponding function and call the method in browser.ts.

/**
 * Created by admin on 2016/11/22.
 */
import { Component } from '@angular/core';
import { ViewController, NavParams } from "ionic-angular";

@Component({
  template: `
    <ion-list>
      <button ion-item detail-none (click)="refresh()">Refresh</button>
      <button ion-item detail-none (click)="share()" *ngIf="parentCallback.share">share</button>
      <button ion-item detail-none (click)="close()">Close</button>
    </ion-list>
  `
})
export class BrowserPopoverPage {
  parentCallback: {refresh: () => void, share?: () => void, close: () => void};

  constructor(public viewCtrl: ViewController,
              private navParams: NavParams) {
    this.parentCallback = this.navParams.data.callback;
  }

  // Refresh
  refresh() {
    this.parentCallback.refresh();
    this.viewCtrl.dismiss();
  }

  // share
  share() {
    this.parentCallback.share();
    this.viewCtrl.dismiss();
  }

  close() {
    this.viewCtrl.dismiss();
    this.parentCallback.close();
  }
}

Define ShareModel Model Model

The share model here is mainly used as the type of parameter passed into browser when calling share.

/**
 * Created by admin on 2017/1/18.
 */

export class ShareModel { // share
  title: string; // Title
  banner: string; // Slogans prompt
  descr: string; // describe
  thumb: string; // Shown thumbnails
  url: string; // link
}

Use examples of BrowserPage

Basic use:

this.navCtrl.push(this.browserPage, {
                browser: {
                    title: 'page name',
                    url: 'Place access page links here'
                }
            });

Add "Sharing" function:

let share: ShareModel = new ShareModel();
            share.title = 'Title';
            share.banner = 'Slogans prompt';
            share.thumb = 'thumbnail';
            share.descr = 'describe';
            share.url = 'Shared links';
            this.navCtrl.push(this.browserPage, {
                browser: {
                    title: 'page name',
                    url: 'Place access page links here',
                    share: share
                }
            });

Use effect of BrowserPage

Open a page:

Open the menu:

Call Sharing, Share Page Links:

Posted by HokieTracks on Fri, 12 Apr 2019 03:30:31 -0700