Javascript 当URI太长时,Chrome崩溃
我正在为我的HTML5游戏制作一个导出函数,我当前的保存方法是对游戏数据进行粗略的序列化,然后:Javascript 当URI太长时,Chrome崩溃,javascript,html,Javascript,Html,我正在为我的HTML5游戏制作一个导出函数,我当前的保存方法是对游戏数据进行粗略的序列化,然后: // this is Javascript var gameData = "abc"; // this is actually a HUGE string of over 2MB try { document.location = "data:text/octet-stream,"+encodeURIComponent(JSON.stringify(gameData)); } catch(e
// this is Javascript
var gameData = "abc"; // this is actually a HUGE string of over 2MB
try
{
document.location = "data:text/octet-stream,"+encodeURIComponent(JSON.stringify(gameData));
}
catch(e)
{
console.log(e);
}
发件人:
我不介意我不能将其用于大字符串,但我希望它生成一个警告,通知此方法不起作用,不幸的是,Chrome(16)崩溃而没有捕获该异常
有没有更好的方法来实现这种出口,对我来说重要的是让它在当地发挥作用。将是一个更好的解决方案,但在本地不起作用。AFAIK不可能在客户端实现;但是一个1.99MB的文件可以通过这种方式保存在Chrome中;也许你应该试着压缩/优化一下你的游戏数据。一种方法是使用 为了检查当前浏览器是否为Google Chrome,因此该方法不适用于长字符串,您可以使用如下内容:
if(gameData.length > 1999999 && window.chrome){
alert("Sorry, this export method does not work in Google Chrome")
return;
}
我假设json.stringify正在工作 但是win.location失败是因为URI太大了 您可以做的是将uri转换为blob,然后
URL.createObjectURL(file)
这将创建指向内部对象(浏览器内部)的url
它将按预期工作
下面是一个将dataURI转换为blob的方法
function(dataURI) {
// convert base64 to raw binary data held in a string
// doesn't handle URLEncoded DataURIs
var byteString;
if (dataURI.split(',')[0].indexOf('base64') >= 0)
byteString = atob(dataURI.split(',')[1]);
else
byteString = unescape(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to an ArrayBuffer
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
// write the ArrayBuffer to a blob, and you're done
return new Blob([ab],{type: mimeString});
}
函数(dataURI){
//将base64转换为字符串中的原始二进制数据
//不处理URL编码的数据URI
var-byteString;
if(dataURI.split(',')[0].indexOf('base64')>=0)
byteString=atob(dataURI.split(',)[1]);
其他的
byteString=unescape(dataURI.split(',)[1]);
//分离出mime组件
var mimeString=dataURI.split(',')[0]。split(':')[1]。split(';')[0];
//将字符串的字节写入ArrayBuffer
var ab=新阵列缓冲区(byteString.length);
var ia=新的UINT8阵列(ab);
for(var i=0;i
}到底什么是崩溃
document.location=
或encodeURI
?要导出到哪里?服务器端?只保存客户端?显然他想导出客户端。崩溃的是document.location为什么不使用客户端存储而不是最好的黑客攻击?您是否担心用户清除数据?为什么不使用localStorage
对象<代码>localStorage.setItem('gameData',JSON.stringify(gameData))然后使用gameData=JSON.parse(localStorage.getItem('gameData')将其取回代码>我不介意它不起作用,我知道如何使保存文件变小,但我不希望它崩溃,除了try/catch
,我不知道其他方法。Chrome崩溃的程度比JavaScript代码更深。你不能抓住这个错误;你只能尽你最大的努力避免导致它的情况。