ステップ 4: WebView で外部リンクを開く

このステップでは、次のことを学びます。

  • 安全でサンドボックス化された方法で、アプリ内に外部ウェブ コンテンツを表示する方法。

この手順の所要時間: 10 分
このステップの内容を確認するには、このページの一番下に移動 ↓ をクリックしてください。

WebView タグについて

一部のアプリでは、外部ウェブ コンテンツをユーザーに直接表示しつつ、アプリ内エクスペリエンス内に保持する必要があります。たとえば、ニュース アグリゲータは、外部サイトからのニュースを、元のサイトのすべての形式、画像、動作とともに埋め込むことができます。こうした用途やその他の用途のために、Chrome アプリには webview というカスタム HTML タグがあります。

WebView を使用する ToDo アプリ

WebView タグを実装する

Todo アプリを更新して、ToDo アイテムのテキスト内の URL を検索し、ハイパーリンクを作成します。このリンクをクリックすると、新しい Chrome アプリのウィンドウ(ブラウザタブではなく)が開き、コンテンツを表示する WebView が表示されます。

許可を更新

manifest.json で、webview 権限をリクエストします。

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

WebView 埋め込みページを作成する

プロジェクト フォルダのルートに新しいファイルを作成し、webview.html という名前を付けます。このファイルは、1 つの <webview> タグを含む基本的なウェブページです。

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

ToDo アイテム内の URL の解析

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://」で始まる文字列が見つかった場合は、URL をラップする HTML アンカータグが作成されます。

controller.jsshowAll() を見つけます。前に追加した _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() で、ラベルの innerHTML ではなくラベルの innerText を使用するようにコードを修正します。

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() コールバックで、WebView の URL が src タグ属性によってどのように設定されるかに注意してください。

最後に、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:// で始まる完全な URL を使用して ToDo アイテムを追加すると、次のように表示されます。

詳細情報

このステップで説明した API の詳細については、以下をご覧ください。

次のステップに進む準備はできましたか?ステップ 5 - ウェブから画像を追加する » に進みます。