I'm writing a Chrome App using AngularJS. I know that when accessing external images you have to do a cross-origin XMLHttpRequest and serve them as blobs.
I have a bunch of internal images (local app resources) that follow a pattern that I want to display in an ngRepeat.
I can get the images to load statically just fine with something like:
<img src="images/image1.png"/>
But when I try using them in a repeat like this:
<div ng-repeat="item in myList">
<img ng-src="{{item.imageUrl}}"/>
</div>
I get an error for each image (though the image from the error does exist) like this:
Refused to load the image 'unsafe:chrome-extension://hcdb...flhk/images/image1.png' because it violates the following Content Security Policy directive: "img-src 'self' data: chrome-extension-resource:".
I have been able to load external resources successfully using ng-src and XHR. Do I have to follow the same pattern for internal resources loaded dynamically?
Starting with the simplest Chrome App (https://github.com/GoogleChrome/chrome-app-samples/tree/master/hello-world), the following will work outside a chrome app (in the browser) but not within the chrome app:
index.html
<!DOCTYPE html>
<html ng-app ng-csp>
<head>
<title>Hello World</title>
<script src="js/angular.min.js"></script>
<script src="js/test.js"></script>
</head>
<body ng-controller="Ctrl">
<img ng-src="{{imageUrl}}"/>
</body>
</html>
test.js
function Ctrl($scope) {
$scope.imageUrl = 'hello_world.png';
}
I just found the answer in another stack overflow question:
Angular changes urls to "unsafe:" in extension page
Angular has a whitelist regular expression that an image src url must match before angular will change the src. A chrome-extension:// url doesn't match it by default so you have to change it. See here for more information:
http://docs.angularjs.org/api/ng/provider/$compileProvider
I added the following code to allow chrome-extension// urls to the whitelist (using the code from the other stackoverflow question's answer):
angular.module('myApp', [])
.config( [
'$compileProvider',
function( $compileProvider ) {
var currentImgSrcSanitizationWhitelist = $compileProvider.imgSrcSanitizationWhitelist();
var newImgSrcSanitizationWhiteList = currentImgSrcSanitizationWhitelist.toString().slice(0,-1)
+ '|chrome-extension:'
+currentImgSrcSanitizationWhitelist.toString().slice(-1);
console.log("Changing imgSrcSanitizationWhiteList from "+currentImgSrcSanitizationWhitelist+" to "+newImgSrcSanitizationWhiteList);
$compileProvider.imgSrcSanitizationWhitelist(newImgSrcSanitizationWhiteList);
}
]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With