Langkah 4: Buka Link Eksternal dengan Webview

Pada langkah ini, Anda akan mempelajari:

  • Cara menampilkan konten web eksternal di dalam aplikasi dengan cara yang aman dan dalam sandbox.

Perkiraan waktu untuk menyelesaikan langkah ini: 10 menit.
Untuk melihat pratinjau apa yang akan Anda selesaikan pada langkah ini, turun ke bagian bawah halaman ini ↓.

Mempelajari tag webview

Beberapa aplikasi perlu menyajikan isi web eksternal secara langsung kepada pengguna tetapi menyimpannya di dalam pengalaman penggunaan aplikasi. Misalnya, agregator berita mungkin ingin menyematkan berita dari sumber eksternal di situs dengan semua format, gambar, dan perilaku situs asal. Untuk aplikasi ini dan lainnya penggunaan, Aplikasi Chrome memiliki tag HTML kustom yang disebut webview.

Aplikasi Todo yang menggunakan webview

Mengimplementasikan tag webview

Update aplikasi Daftar tugas untuk menelusuri URL di teks item daftar tugas dan membuat hyperlink. Tautan, ketika diklik, membuka jendela Aplikasi Chrome baru (bukan tab browser) dengan webview yang menyajikan konten.

Update izin

Di manifest.json, minta izin webview:

"permissions": [
  "storage",
  "alarms",
  "notifications",
  "webview"
],

Membuat halaman sematan webview

Buat file baru di root folder project Anda dan beri nama webview.html. File ini adalah halaman web dasar dengan satu tag <webview>:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
</head>
<body>
  <webview style="width: 100%; height: 100%;"></webview>
</body>
</html>

Mengurai URL dalam item daftar tugas

Di akhir controller.js, tambahkan metode baru bernama _parseForURLs():

  Controller.prototype._getCurrentPage = function () {
    return document.location.hash.split('/')[1];
  };

  Controller.prototype._parseForURLs = function (text) {
    var re = /(https?:\/\/[^\s"<>,]+)/g;
    return text.replace(re, '<a href="$1" data-src="$1">$1</a>');
  };

  // Export to window
  window.app.Controller = Controller;
})(window);

Setiap kali string yang dimulai dengan "http://" atau "https://" ditemukan, tag anchor HTML dibuat untuk membungkus URL.

Cari showAll() di controller.js. Perbarui showAll() untuk mengurai link dengan menggunakan Metode _parseForURLs() ditambahkan sebelumnya:

/**
 * An event to fire on load. Will get all items and display them in the
 * todo-list
 */
Controller.prototype.showAll = function () {
  this.model.read(function (data) {
    this.$todoList.innerHTML = this.view.show(data);
    this.$todoList.innerHTML = this._parseForURLs(this.view.show(data));
  }.bind(this));
};

Lakukan hal yang sama untuk showActive() dan showCompleted():

/**
 * Renders all active tasks
 */
Controller.prototype.showActive = function () {
  this.model.read({ completed: 0 }, function (data) {
    this.$todoList.innerHTML = this.view.show(data);
    this.$todoList.innerHTML = this._parseForURLs(this.view.show(data));
  }.bind(this));
};

/**
 * Renders all completed tasks
 */
Controller.prototype.showCompleted = function () {
  this.model.read({ completed: 1 }, function (data) {
    this.$todoList.innerHTML = this.view.show(data);
    this.$todoList.innerHTML = this._parseForURLs(this.view.show(data));
  }.bind(this));
};

Terakhir, tambahkan _parseForURLs() ke editItem():

Controller.prototype.editItem = function (id, label) {
  ...
  var onSaveHandler = function () {
    ...
      // Instead of re-rendering the whole view just update
      // this piece of it
      label.innerHTML = value;
      label.innerHTML = this._parseForURLs(value);
    ...
  }.bind(this);
  ...
}

Masih di editItem(), perbaiki kode agar menggunakan innerText pada label, bukan innerHTML label:

Controller.prototype.editItem = function (id, label) {
  ...
  // Get the innerHTML of the label instead of requesting the data from the
  // Get the innerText of the label instead of requesting the data from the
  // ORM. If this were a real DB this would save a lot of time and would avoid
  // a spinner gif.
  input.value = label.innerHTML;
  input.value = label.innerText;
  ...
}

Membuka jendela baru yang berisi webview

Tambahkan metode _doShowUrl() ke controller.js. Metode ini membuka jendela Aplikasi Chrome baru melalui chrome.app.window.create() dengan webview.html sebagai sumber jendela:

  Controller.prototype._parseForURLs = function (text) {
    var re = /(https?:\/\/[^\s"<>,]+)/g;
    return text.replace(re, '<a href="$1" data-src="$1">$1</a>');
  };

  Controller.prototype._doShowUrl = function(e) {
    // only applies to elements with data-src attributes
    if (!e.target.hasAttribute('data-src')) {
      return;
    }
    e.preventDefault();
    var url = e.target.getAttribute('data-src');
    chrome.app.window.create(
     'webview.html',
     {hidden: true},   // only show window when webview is configured
     function(appWin) {
       appWin.contentWindow.addEventListener('DOMContentLoaded',
         function(e) {
           // when window is loaded, set webview source
           var webview = appWin.contentWindow.
                document.querySelector('webview');
           webview.src = url;
           // now we can show it:
           appWin.show();
         }
       );
     });
  };

  // Export to window
  window.app.Controller = Controller;
})(window);

Di callback chrome.app.window.create(), perhatikan cara URL webview ditetapkan melalui tag src Anda.

Terakhir, tambahkan pemroses peristiwa klik di dalam konstruktor Controller untuk memanggil doShowUrl() saat pengguna mengeklik tautan:

function Controller(model, view) {
  ...
  this.router = new Router();
  this.router.init();

  this.$todoList.addEventListener('click', this._doShowUrl);

  window.addEventListener('load', function () {
    this._updateFilterState();
  }.bind(this));
  ...
}

Meluncurkan aplikasi Daftar Tugas yang sudah selesai

Anda sudah menyelesaikan Langkah 4! Jika Anda memuat ulang aplikasi dan menambahkan item daftar tugas dengan URL lengkap yang dimulai dengan http:// atau https://, Anda akan melihat seperti ini:

Untuk informasi selengkapnya

Untuk informasi yang lebih mendetail tentang beberapa API yang diperkenalkan di langkah ini, lihat:

Siap untuk melanjutkan ke langkah berikutnya? Lanjutkan ke Langkah 5 - Tambahkan gambar dari web »