4단계: WebView로 외부 링크 열기

이 단계에서 학습할 내용은 다음과 같습니다.

  • 안전한 샌드박스 방식으로 앱 내에 외부 웹 콘텐츠를 표시하는 방법

이 단계를 완료하는 데 필요한 예상 시간: 10분
이 단계에서 완료할 작업을 미리 보려면 이 페이지 하단으로 이동 ↓하세요.

WebView 태그에 대해 알아보기

일부 애플리케이션은 외부 웹 콘텐츠를 사용자에게 직접 표시하고 살펴봤습니다 예를 들어 뉴스 애그리게이터는 외부의 뉴스를 삽입하고 원본 사이트의 모든 형식, 이미지, 동작을 포함한 사이트 이 항목 및 기타 Chrome 앱에는 webview라는 맞춤 HTML 태그가 있습니다.

WebView를 사용하는 Todo 앱

WebView 태그 구현

Todo 앱을 업데이트하여 할 일 항목 텍스트에서 URL을 검색하고 하이퍼링크를 만듭니다. 링크, 클릭하면 콘텐츠를 보여주는 WebView와 함께 새 Chrome 앱 창이 열립니다 (브라우저 탭이 아님).

권한 업데이트

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://' 가 발견되면 이를 위해 HTML 앵커 태그가 생성됩니다. URL을 둘러쌉니다.

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));
};

마지막으로 editItem()_parseForURLs()를 추가합니다.

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 앱 창을 엽니다. chrome.app.window.create()를 창 소스로 사용하여 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));
  ...
}

완성된 할 일 앱 실행

4단계가 완료되었습니다. 앱을 새로고침하고 http:// 또는 https://를 사용할 경우 다음과 같이 표시됩니다.

추가 정보

이 단계에서 도입된 일부 API에 관한 자세한 내용은 다음을 참조하세요.

다음 단계를 진행할 준비가 되셨나요? 5단계 - 웹에서 이미지 추가 »로 이동합니다.