Access Web Resources
Chrome Apps have a strict Content Security Policy which will not let the user execute code or load resources that are hosted remotely.
Many applications, however, need to be able to load and display content from a remote location. A News Reader, for example, needs to display remote content inline or load and show images from a remote URL.
Load external web content
Sites on the internet are inherently a security risk and rendering arbitrary web pages directly into your application with elevated privileges would be a potential source of exploits.
Chrome Apps offer developers the ability
to securely render third-party content in the <webview>
tag.
A webview
is like an iframe that you can control with greater flexibility and added security.
It runs in a separate sandboxed process and can't communicate directly with the application.
The webview
has a very simple API.
From your app you can:
- Change the URL of the
webview
. - Navigate forwards and backward, stop loading and reload.
- Check if the
webview
has finished loading and if it is possible, go back and forward in the history stack.
We will change our code to render the content of URLs dropped
in the drag-and-drop operations in a webview
when the user clicks on a link.
Update manifest
Request a new permission, "webview", in the manifest. Angular JS manifest.json and JavaScript manifest.json are the same:
"permissions": ["storage", "webview"]
Update view
Add a <webview>
tag and a link to the view:
AngularJS index.html or
JavaScript index.html:
<!-- in TODO item: --> <a ng-show="todo.uri" href="" ng-click="showUri(todo.uri)">(view url)</a> <!-- at the bottom, below the end of body: --> <webview></webview>
<!-- right after the "dropText" div: --> <webview></webview> <!-- in the TODO template, right before the end of the li: --> <a style="display: none;" href="">(view url)</a>
Update stylesheet
Set an appropriate width and height to the <webview>
tag in
the style sheet.
AngularJS todo.css and
JavaScript todo.css are the same:
webview { width: 100%; height: 200px; }
Update controller
We now only need to add a method,
showUri
, to the
AngularJS controller.js
or an event handler, showUrl
, to the
JavaScript controller.js.
$scope.showUri = function(uri) { var webview=document.querySelector("webview"); webview.src=uri; };
if(/^http:\/\/|https:\/\//.test(todoObj.text)) { var showUrl = el.querySelector('a'); showUrl.addEventListener('click', function(e) { e.preventDefault(); var webview=document.querySelector("webview"); webview.src=todoObj.text; }); showUrl.style.display = 'inline'; }
Check the results
To test, open the app, right-click, and select Reload App.
You should be able to click on the "view url" link
on any dropped URL Todo item,
and the corresponding web page will show in the webview
.
If it's not showing,
inspect the page and check if you set the webview
size appropriately.
If you get stuck and want to see the app in action,
go to chrome://extensions
,
load the unpacked
AngularJS 1_webview or
JavaScript 1_webview,
and launch the app from a new tab.
Load external images
If you try to add an <img>
tag to your index.html
, and point its src
attribute to any site on the web, the following exception is thrown in the console and the image isn't loaded:
Refused to load the image 'http://angularjs.org/img/AngularJS-large.png' because it violates the following Content Security Policy directive: "img-src 'self' data: chrome-extension-resource:".
Chrome Apps cannot load any external resource directly in the DOM, because of the CSP restrictions.
To avoid this restriction, you can use XHR requests, grab the blob corresponding to the remote file and use it appropriately.
For example, <img>
tags can use a blob URL.
Let's change our application to show a small icon in the Todo list if the dropped URL represents an image.
Update manifest
Before you start firing XHR requests, you must request permissions. Since we want to allow users to drag and drop images from any server, we need to request permission to XHR to any URL. Change AngularJS manifest.json or JavaScript manifest.json:
"permissions": ["storage", "webview", "<all_urls>"]
Add image
Add to your project a placeholder image that will be shown while we are loading the proper image.
Then add the <img>
tag to the Todo item on the view:
AngularJS index.html or
JavaScript index_html:
<img style="max-height: 48px; max-width: 120px;" ng-show="todo.validImage" ng-src="{{todo.imageUrl}}"></img>
<img style="max-height: 48px; max-width: 120px;"></img>
In the JavaScript controller.js, add a constant for the placeholder image:
const PLACEHOLDER_IMAGE = "loading.gif";
As you will see soon,
this element is only shown when the validImage
attribute of the Todo item is true.
Update controller
Add the method loadImage
to a new script file
that will start a XHR request and execute a callback with a Blob URL.
AngularJS loader.js and
JavaScript loader.js are the same:
var loadImage = function(uri, callback) { var xhr = new XMLHttpRequest(); xhr.responseType = 'blob'; xhr.onload = function() { callback(window.URL.createObjectURL(xhr.response), uri); } xhr.open('GET', uri, true); xhr.send(); }
In the AngularJS controller.js or JavaScript controller.js, add a new method that will search the Todo list looking for images that are not loaded yet:
// for each image with no imageUrl, start a new loader $scope.loadImages = function() { for (var i=0; i<$scope.todos.length; i++) { var todo=$scope.todos[i]; if (todo.validImage && todo.imageUrl===PLACEHOLDER_IMAGE) { loadImage(todo.uri, function(blob_uri, requested_uri) { $scope.$apply(function(scope) { for (var k=0; k<scope.todos.length; k++) { if (scope.todos[k].uri==requested_uri) { scope.todos[k].imageUrl = blob_uri; } } }); }); } } };
var maybeStartImageLoader = function(el, todo) { var img = el.querySelector('img'); if (todo['extras'] && todo.extras.validImage && todo.extras.imageUrl) { if (todo.extras.imageUrl===PLACEHOLDER_IMAGE) { img.src = PLACEHOLDER_IMAGE; img.style.display = 'inline'; window.loadImage(todo.extras.uri, function(blob_uri, requested_uri) { todo.extras.imageUrl = blob_uri; img.src = blob_uri; }); } else { img.src = todo.extras.imageUrl; img.style.display = 'inline'; } } else { img.style.display = 'none'; } };
If writing your app in JavaScript,
you will need to call the maybeStartImageLoader
function
in the
JavaScript controller.js
to update the Todo list from the model:
var updateTodo = function(model) { var todoElement = list.querySelector('li[data-id="'+model.id+'"]'); if (todoElement) { var checkbox = todoElement.querySelector('input[type="checkbox"]'); var desc = todoElement.querySelector('span'); checkbox.checked = model.isDone; desc.innerText = model.text; desc.className = "done-"+model.isDone; // load image, if this ToDo has image data maybeStartImageLoader(todoElement, model); } }
Then in the
AngularJS controller.js or
JavaScript.controller.js,
drop()
method,
change the handling of URIs to appropriately detect a valid image.
For simplicity sake, we only tested for png and jpg extensions.
Feel free to have a better coverage in your code.
var uri=e.dataTransfer.getData("text/uri-list"); var todo = {text:uri, done:false, uri: uri}; if (/.png$/.test(uri) || /.jpg$/.test(uri)) { hasImage = true; todo.validImage = true; todo.imageUrl = PLACEHOLDER_IMAGE; } newTodos.push(todo); // [...] inside the $apply method, before save(), call the loadImages method: $scope.loadImages();
var uri = e.dataTransfer.getData("text/uri-list"); var extras = { uri: uri }; if (/\.png$/.test(uri) || /\.jpg$/.test(uri)) { hasImage = true; extras.validImage = true; extras.imageUrl = PLACEHOLDER_IMAGE; } model.addTodo(uri, false, extras);
And, finally, we will change the load method to reset the Blob URLs, since Blob URLs don't span through sessions. Setting Todo's imageUrls to the PLACEHOLDER_IMAGE will force the loadImages method to request them again:
// If there is saved data in storage, use it. Otherwise, bootstrap with sample todos $scope.load = function(value) { if (value && value.todolist) { // ObjectURLs are revoked when the document is removed from memory, // so we need to reload all images. for (var i=0; i<value.todolist.length; i++) { value.todolist[i].imageUrl = PLACEHOLDER_IMAGE; } $scope.todos = value.todolist; $scope.loadImages(); } else { $scope.todos = [ {text:'learn angular', done:true}, {text:'build an angular app', done:false}]; } }
/** * Listen to changes in the model and trigger the appropriate changes in the view **/ model.addListener(function(model, changeType, param) { if ( changeType === 'reset' ) { // let's invalidate all Blob URLs, since their lifetime is tied to the document's lifetime for (var id in model.todos) { if (model.todos[id].extras && model.todos[id].extras.validImage) { model.todos[id].extras.imageUrl = PLACEHOLDER_IMAGE; } } } if ( changeType === 'removed' || changeType === 'archived' || changeType === 'reset') { redrawUI(model); } else if ( changeType === 'added' ) { drawTodo(model.todos[param], list); } else if ( changeType === 'stateChanged') { updateTodo(model.todos[param]); } storageSave(); updateCounters(model); });
Check the results
To test, open the app, right-click, and select Reload App. Go to Google images, search for and select an image, then drag and drop the image into the Todo list app. Assuming no mistakes were made, you should now have a thumbnail of every image URL dropped into the Todo list app.
Notice we are not handling local images dropped from the file manager in this change. We leave this as a challenge for you.
If you get stuck and want to see the app in action,
go to chrome://extensions
, load the unpacked
AngularJS 2_loading_resources or,
JavaScript 2_loading_resources
and launch the app from a new tab.
The loadImage()
method above is not the best solution for this problem, because it doesn't handle errors correctly and it could cache images in a local filesystem.
We've created the
apps-resource-loader library
that's much more robust.
Takeaways
The
<webview>
tag allows you to have a controlled browser inside your app. You can use it if you have part of your application that is not CSP compatible and you don't have resources to migrate it immediately, for example. One feature we didn't mention here is that webviews can communicate with your app and vice-versa using asynchronous postMessages.Loading resources like images from the web is not straightforward compared to a standard web page. But it's not too different from traditional native platforms, where you need to handle the resource download and, only when it is correctly downloaded, you can render it in the UI. We have also developed a sample library to asynchronously handle resource loading from XHR calls. Feel free to use it in your projects.
You should also read
- Webview Tag API reference
- Embed Content tutorial
What's next?
In 8 - Publish App, we finish off with instructions on how to publish your app in the Chrome Web Store.