サンプル
console.logを使う
コード
var loader={
xhr: function(){
return new XMLHttpRequest();
},
download: function(url, key, tag){
var req=this.xhr();
req.open('GET', url, false);
req.overrideMimeType('text/plain; charset=x-user-defined');
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 saveAudio(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 playAudio(key){
//console.log( localStorage[key] );
if( !loader.has(key) ){
alert('can not play');
return false;
}
var audio=new Audio(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);
loader.save(key, canvas.toDataURL(mime));
return true;
}
function showImage(key){
//console.log( localStorage[key] );
var img=new Image();
img.src=loader.get(key);
document.getElementById('output').appendChild(img);
}
/**/
var key1='audio1';
var key2='image2';
var key3='image3';
onload= function(){
if( !loader.has(key1) ){
saveAudio(key1, document.getElementsByTagName('audio')[0]);
}
if( !loader.has(key2) ){
saveImage(key2, document.images[0], 'image/png');
}
if( !loader.has(key3) ){
saveImageFromNetwork(key3, document.getElementsByTagName('img')[0], 'image/png');
}
//playAudio(key1);
//showImage(key2);
//showImage(key3);
};/*onload*/