ステップ 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 に追加します。このメソッドは、webview.html をウィンドウ ソースとする新しい Chrome アプリのウィンドウを、chrome.app.window.create() を介して開きます。

  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 の URL がどのように設定されているかを確認します。

最後に、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 - ウェブから画像を追加する » に進みます。