Langkah 4: Buka Link Eksternal dengan Webview

Pada langkah ini, Anda akan mempelajari:

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

Perkiraan waktu untuk menyelesaikan langkah ini: 10 menit.
Untuk melihat pratinjau tugas yang akan Anda selesaikan di langkah ini, langsung ke bagian bawah halaman ini ↓.

Mempelajari tag webview

Beberapa aplikasi perlu menampilkan konten web eksternal secara langsung kepada pengguna, tetapi mempertahankannya di dalam pengalaman aplikasi. Misalnya, agregator berita mungkin ingin menyematkan berita dari situs eksternal dengan semua pemformatan, gambar, dan perilaku situs asalnya. Untuk penggunaan ini dan lainnya, Aplikasi Chrome memiliki tag HTML kustom yang disebut webview.

Aplikasi Todo menggunakan webview

Menerapkan tag webview

Perbarui aplikasi Daftar Tugas untuk menelusuri URL di teks item daftar tugas dan buat hyperlink. Jika diklik, link akan 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 penyemat 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>

Uraikan 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 ditemukan string yang dimulai dengan "http://" atau "https://", tag anchor HTML dibuat untuk menggabungkan URL.

Cari showAll() di controller.js. Perbarui showAll() untuk mengurai link menggunakan metode _parseForURLs() yang 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));
};

Dan 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 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);

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

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

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));
  ...
}

Luncurkan aplikasi Daftar tugas yang telah selesai

Anda 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 tampilan seperti ini:

Untuk informasi selengkapnya

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

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