Nesta etapa, você vai aprender:
- Como mostrar conteúdo da Web externo no seu app de maneira segura e no sandbox.
Tempo estimado para concluir esta etapa: 10 minutos.
Para visualizar o que você concluirá nesta etapa, vá para a parte inferior desta página ↓.
Saiba mais sobre a tag WebView
Alguns aplicativos precisam apresentar conteúdo externo da Web diretamente ao usuário, mas mantê-lo dentro do usuário final. Por exemplo, um agregador de notícias pode querer incorporar notícias de sites externos sites com toda a formatação, as imagens e o comportamento do site original. Para estes e outros usos, os Aplicativos do Google Chrome têm uma tag HTML personalizada chamada WebView.
Implementar a tag WebView
Atualize o app Todo para pesquisar URLs no texto do item de tarefas e criar um hiperlink. O link, quando clicado, abre uma nova janela do aplicativo do Google Chrome (não uma guia do navegador) com um WebView apresentando o conteúdo.
Atualizar permissões
Em manifest.json, solicite a permissão webview
:
"permissions": [
"storage",
"alarms",
"notifications",
"webview"
],
Criar uma página do incorporador do WebView
Crie um novo arquivo na raiz da pasta do projeto e nomeie-o como webview.html. Este arquivo é um
página da Web básica com uma tag <webview>
:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<webview style="width: 100%; height: 100%;"></webview>
</body>
</html>
Analisar URLs em itens de tarefas
No final do controller.js, adicione um novo método com o nome _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);
Sempre que uma string que começa com "http://" ou "https://" é encontrada, uma tag âncora HTML é criada para ao redor do URL.
Renderizar hiperlinks na lista de tarefas
Encontre showAll()
em controller.js. Atualize showAll()
para analisar links usando o método
Método _parseForURLs()
adicionado anteriormente:
/**
* 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));
};
Faça o mesmo para showActive()
e 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));
};
Por fim, adicione _parseForURLs()
a 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);
...
}
Ainda no editItem()
, corrija o código para que ele use o innerText
do rótulo em vez do
innerHTML
do rótulo:
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;
...
}
Abrir nova janela contendo o WebView
Adicione um método _doShowUrl()
ao controller.js. Esse método abre uma nova janela de app do Chrome no
chrome.app.window.create() com webview.html como origem da janela:
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);
No callback chrome.app.window.create()
, observe como o URL do WebView é definido pela tag src
.
atributo.
Por fim, adicione um listener de eventos de clique no construtor Controller
para chamar doShowUrl()
quando uma
o usuário clica em um link:
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));
...
}
Iniciar o app Todo concluído
Você concluiu a Etapa 4! Se você recarregar o app e adicionar um item de tarefas com um URL completo que começa com http:// ou https://, você verá algo parecido com isto:
Mais informações
Para informações mais detalhadas sobre algumas das APIs introduzidas nesta etapa, consulte:
Tudo pronto para passar para a próxima etapa? Acesse a Etapa 5: adicionar imagens da Web »