当用户按下ctrl + s键但Chrome崩溃时,我正在尝试将HTML文件保存在Chrome中。

(我只想下载我的HTML文件的源代码)

我读到发生这种情况是因为我的文件大于1.99M。

第一次尝试(在我知道Chrome崩溃之前):

function download(filename, text) {
    var pom = document.createElement('a');
    pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
    pom.setAttribute('download', filename);
    pom.click();
}

download('test.html', "<html>" + document.getElementsByTagName('html')[0].innerHTML + "</html>");

,第二次尝试,当我了解到崩溃信息后,我使用了blob:
function dataURItoBlob(dataURI) {
    var byteString = atob(dataURI.split(',')[1]);

    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]

    var ab = new ArrayBuffer(byteString.length);
    var ia = new Uint8Array(ab);
    for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }

    var bb = new BlobBuilder();
    bb.append(ab);
    return bb.getBlob(mimeString);
}

function download(dataURI) {
    var blob = dataURItoBlob(dataURI);
    var url  = window.URL.createObjectURL(blob);
    window.location.assign(url);
}

download("<html>" + document.getElementsByTagName('html')[0].innerHTML + "</html>")

在这里我得到了错误:Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.
我不知道,但是我读到我需要将字符串编码为base64:How can you encode a string to Base64 in JavaScript?

答案是148票。我将其粘贴到代码中,不知道如何继续。

我应该在哪里叫它,怎么称呼它?我可以在保存的文件上加上名称吗?

我认为我需要做类似的事情:
download(_utf8_decode("<html>" + document.getElementsByTagName('html')[0].innerHTML + "</html>"))

最佳答案

BlobBuilder 已过时,请改用 Blob constructor:

URL.createObjectURL(new Blob([/*whatever content*/] , {type:'text/plain'}));

这将返回一个Blob URL,您可以将其用于 anchor 的href中。您还可以修改 anchor 的download属性以操纵文件名:
<a href="/*assign url here*/" id="link" download="whatever.txt">download me</a>

Fiddled。如果我没记错的话,对受信任的非用户启动的下载有任意限制;因此,我们将坚持点击链接,这被认为是用户充分启动的:)

更新:实际上,保存当前文档的html非常简单!每当单击我们的交互式链接时,我们都会使用相关的Blob更新其href。执行点击绑定(bind)事件后,这就是将导航到的下载URL!
$('#link').on('click', function(e){
  this.href = URL.createObjectURL(
    new Blob([document.documentElement.outerHTML] , {type:'text/html'})
  );
});

Fiddled again

关于javascript - 无法在 'atob'上执行 'Window',我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22578530/

10-11 22:46
查看更多