【经验】在Chrome apps中如何加载外部图片资源

点击查看原图

在Chrome App中如果直接直接加载外部图片文件(无论是写在样式中,或是直接img标签载入,<webview>除外),都会报如下错误:

Refused to load the image 'http://xxx.jpg' because it violates the following Content Security Policy directive: "img-src 'self' data: chrome-extension-resource:".

原因不用多解释了,提示很清楚了,根据内容安全策略,禁止直接载入外部资源。

 

解决方案:

通过XMLHttpRequest 以blob:, data:, or 文件系统URLs的格式载入资源。

Chrome 团队已经封装好了一个库供开发者使用:Chrome Packaged Apps Resource Loader

var remoteImage, 
    container = document.querySelector('.imageContainer'),
    toLoad = { 'images': [ 
       'http://myserver.com/image1.png', 
       'http://myserver.com/image2.png' ] }; // list of image URLs

toLoad.images.forEach(function(imageToLoad) {
      remoteImage = new RAL.RemoteImage(imageToLoad);
      container.appendChild(remoteImage.element);
      RAL.Queue.add(remoteImage);
});
RAL.Queue.setMaxConnections(4);
RAL.Queue.start();
注意加上权限:

permissions: ['<all_urls>'],

如果只想简单的使用,没有这么多需求而去载入一个库,可以简单的封装一个函数来处理:

function loadImage(uri,callback){
	if(typeof callback!='function'){
		callback=function(uri){
			console.log(uri);
		}
	}
	var xhr = new XMLHttpRequest();
	xhr.responseType = 'blob';
	xhr.onload = function() {
		callback(window.URL.createObjectURL(xhr.response));
	}
	xhr.open('GET', uri, true);
	xhr.send();
}

//使用方法
var imgUrl='http:xxx.jpg';
loadImage(imgUrl,function(URI){
	//Do some thing while image is load
});

 



阅读本文后,您的心情是:
 
恶心
愤怒
强赞
感动
路过
无聊
雷囧
关注
知识共享许可协议
评论(0) 浏览(44676) 引用(0)
引用地址:http://blog.baiwand.com/tb.php?sc=3db3fc&id=225
Tags:
« 【解决】zepto的tap“点透”问题终极解决方案 【收藏】Sublime Text全套快捷键 »

Blogger

  • blogger
  • 天之骄子
  • 职位:研发工程师
    铭言:
    阳光与欢乐同在,
    与我同在
    主页:
    blog.baiwand.com

分类目录

日志归档

主题标签

数据统计

  • 日志:151篇
  • 评论:45条
  • 碎语:264条
  • 引用:0条

链接表

随机日志 »

最新日志 »

最新评论 »

标签云 »

订阅Rss
sitemap