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

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

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

完成此步骤的预计用时:10 分钟
如需预览您将在此步骤中完成的内容,请跳至本页面底部 ↓

了解 WebView 代码

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

使用 WebView 的 Todo 应用

实现 WebView 代码

更新待办事项应用以搜索待办事项文本中的网址,并创建超链接。点击后,系统会打开一个新的 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 (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 的新窗口

controller.js 添加 _doShowUrl() 方法。此方法通过 chrome.app.window.create() 打开一个新的 Chrome 应用窗口,其中 webview.html 作为窗口来源:

  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 步 - 从网络添加图片 »