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

이 단계에서는 다음을 알아봅니다.

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

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

WebView 태그에 대해 알아보기

일부 애플리케이션은 외부 웹 콘텐츠를 사용자에게 직접 표시해야 하지만 애플리케이션 환경 내에서 유지해야 합니다. 예를 들어 뉴스 애그리게이터는 원본 사이트의 모든 형식, 이미지, 동작을 포함하여 외부 사이트의 뉴스를 삽입하려고 할 수 있습니다. 이러한 용도와 기타 용도를 위해 Chrome 앱에는 webview라는 맞춤 HTML 태그가 있습니다.

WebView를 사용하는 Todo 앱

WebView 태그 구현

할 일 항목 텍스트에서 URL을 검색하고 하이퍼링크를 만들도록 Todo 앱을 업데이트합니다. 이 링크를 클릭하면 콘텐츠를 표시하는 WebView가 포함된 새 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>

할 일 항목의 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.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));
};

마지막으로 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()에서 계속해서 라벨의 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를 포함하는 새 창 열기

controller.js_doShowUrl() 메서드를 추가합니다. 이 메서드는 webview.html을 창 소스로 사용하여 chrome.app.window.create()를 통해 새 Chrome 앱 창을 엽니다.

  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이 설정되는 방식을 확인합니다.

마지막으로, 사용자가 링크를 클릭할 때 doShowUrl()를 호출하도록 Controller 생성자 내에 클릭 이벤트 리스너를 추가합니다.

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://로 시작하는 전체 URL이 포함된 할 일 항목을 추가하면 다음과 같이 표시됩니다.

추가 정보

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

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