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

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

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

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

了解 WebView 代码

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

使用 WebView 的 Todo 应用

实现 WebView 代码

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

启动完成开发的 Todo 应用

您已完成第 4 步!如果您重新加载应用并添加了以 http:// 或 https:// 开头的完整网址的待办事项,则应该会看到如下内容:

了解详情

如需详细了解本步骤中介绍的部分 API,请参阅:

准备好继续执行下一步了吗?前往第 5 步 - 从网络添加图片 »