第 4 步:使用 WebView 打开外部链接

在此步骤中,您将学习以下内容:

  • 如何以安全和沙盒化的方式在应用中显示外部 Web 内容。

完成此步骤的预计用时:10 分钟。
若要预览您将在此步骤中完成的内容,请跳转到本页底部 ↓

了解 WebView 代码

有些应用需要直接向用户显示外部 Web 内容,但将它们保留在 应用体验例如,新闻聚合器可能希望嵌入来自外部 保留原始网站的所有格式、图片和行为。对于这些 Chrome 应用有一个名为 webview 的自定义 HTML 标记。

使用 WebView 的 Todo 应用

实现 WebView 代码

更新 Todo 应用以搜索待办事项文本中的网址并创建超链接。链接 会打开一个新的 Chrome 应用窗口(而非浏览器标签页),其中包含呈现相应内容的网页视图。

更新权限

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()。更新 showAll() 以使用 之前添加的 _parseForURLs() 方法:

/**
 * 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 (