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

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

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

完成這個步驟的預估時間:10 分鐘。
如要預覽您將在本步驟中完成的內容,請向下滑動至本頁底部 ↓

瞭解 WebView 代碼

有些應用程式需要直接向使用者呈現外部網頁內容,但必須保留在應用程式體驗中。舉例來說,新聞集結網站可能會想嵌入外部網站的新聞,其中包含原始網站的所有格式、圖片和行為。針對這些和其他用途,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()。使用先前新增的 _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() 開啟新的 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 - 從網路新增圖片 »