步驟 4:透過 WebView 開啟外部連結

在這個步驟中,您將瞭解:

  • 如何以安全且沙箱的方式,在應用程式中顯示外部網路內容。

預計完成這個步驟的時間:10 分鐘。
如要預覽這個步驟中要完成的內容,請向下跳到本頁底部 ↓

瞭解 WebView 代碼

有些應用程式必須直接向使用者顯示外部網路內容,但讓他們可以留在應用程式體驗中。舉例來說,新聞匯總工具可能會想嵌入外部網站的新聞,且所有網站的格式、圖片和行為均屬於原始網站。上述用途及其他用途:Chrome 應用程式都有名為 webview 的自訂 HTML 標記。

使用 WebView 執行待辦事項應用程式

導入 WebView 代碼

更新待辦事項應用程式,搜尋待辦事項項目文字中的網址並建立超連結。使用者點選連結後,會開啟新的 Chrome 應用程式視窗 (而非瀏覽器分頁),其中有顯示內容的 WebView。

更新權限

manifest.json 中要求 webview 權限:

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

建立 WebView 嵌入器頁面

在專案資料夾的根目錄中建立新檔案,並將其命名為 webview.html。這個檔案是含有一個 <webview> 標記的基本網頁:

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

剖析待辦事項網址

controller.js 結尾,新增名為 _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);

每當找到開頭為「http://」或「https://」的字串時,系統都會建立 HTML 錨定標記來包裝網址。

controller.js 中找到 showAll()。使用先前新增的 _parseForURLs() 方法更新 showAll(),以剖析連結:

/**
 * 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));
};

showActive()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));
};

最後,將 _parseForURLs() 新增至 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);
  ...
}

同樣在 editItem() 中,修正程式碼,讓程式碼使用標籤的 innerText 而非標籤的 innerHTML

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

開啟含有 WebView 的新視窗

_doShowUrl() 方法新增至 controller.js。這個方法會透過 chrome.app.window.create() 以及視窗來源 webview.html 開啟新的 Chrome 應用程式視窗:

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

chrome.app.window.create() 回呼中,請注意透過 src 標記屬性設定 WebView 網址的方式。

最後,在 Controller 建構函式中加入點擊事件監聽器,以便在使用者點選連結時呼叫 doShowUrl()

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

啟動已完成的待辦事項應用程式

您已完成步驟 4!當您重新載入應用程式,並新增網址開頭為 http:// 或 https:// 的待辦事項項目,顯示的內容如下:

瞭解詳情

如要進一步瞭解這個步驟介紹的某些 API,請參閱:

準備好繼續進行下一步了嗎?請參閱步驟 5 - 從網路新增圖片 »