サンプル
console.logを使う
コード
var loader={
xhr: function(){
return new XMLHttpRequest();
},
download: function(url, key, tag){
var req=this.xhr();
req.open('GET', url, false);
req.send(null);
this.save(key, tag+base64encode(req.responseText));
},
save: function(key, value){
localStorage[key] = value;
},
get: function(key){
return localStorage[key];
},
has: function(key){
return Boolean( localStorage[key] );
},
clear: function(key){
if( key ){
delete localStorage[key];
}else{
localStorage.clear();
}
}
};
function saveSound(key, elAudio){
var url, mime;
var elSources=elAudio.getElementsByTagName('source');
for( var i=0, elSource, t, s; elSource=elSources[i]; i++ ){
t=elSource.type;
s=elSource.src;
if( elAudio.canPlayType(t) ){
url=s;
mime=t;
break;
}
}
if( url ){
loader.download(url, key, 'data:'+mime+';base64,');
}
return url;
}
function playSound(key){
if( !loader.has(key) ){
alert('can not play');
return false;
}
//console.log( loader.get(key) );
var audio=new Audio(loader.get(key));
//var audio=new Audio(this.dataTag+base64decode(loader.get(key)));
//var audio=document.getElementsByTagName('audio')[0];
//audio.src=loader.dataTag+loader.get(key);
audio.play();
}
// XHRでダウンロード、エンコード
function saveImageFromNetwork(key, img, mime){
loader.download(img.src, key, 'data:'+mime+';base64,');
return true;
}
// canvas経由でエンコード
function saveImage(key, img, mime){
var canvas=document.createElement('canvas');
canvas.width=img.width; canvas.height=img.height;
canvas.getContext('2d').drawImage(img,0,0);
localStorage[key]=canvas.toDataURL(mime);
return true;
}
function showImage(key){
// XHRで保存した物と、canvas経由で保存した物を比較。
// 違うデータなのが確認できる。
console.log( loader.get(key) );
var img=new Image();
img.src=localStorage[key];
document.getElementById('output').appendChild(img);
}
/**/
var key1='audio1';
var key2='image2';
var key3='image3';
onload= function(){
if( !loader.has(key1) ){
saveSound(key1, document.getElementsByTagName('audio')[0]);
}
saveImage(key2, document.images[0], 'image/png');
if( !loader.has(key3) ){
saveImageFromNetwork(key3, document.getElementsByTagName('img')[0], 'image/png');
}
}/**/