解码不适用于 Base64

Decoding not working with Base64

编码我的 URL 与 base-64 编码完美结合。解码也是如此,但不使用字符串文字变量

这个有效:

document.write(atob("hi"));

这不是:

var tempvar = "hello";
document.write(atob(tempvar));

我做错了什么?什么都不显示。但是,如果我引用 "tempvar",那么它当然有效,但不是一回事,因为 "tempvar" 是一个字符串,而不是一个变量。

因为它无法解码字符串"hello",请尝试使用可以从base64解码的实际字符串,这里是一个例子;

var tempvar = "aHR0cDovL3N0YWNrb3ZlcmZsb3cuY29tL3F1ZXN0aW9ucy80MzEyOTEzNi9kZWNvZGluZy1ub3Qtd29ya2luZy13aXRoLWJhc2U2NA==";
document.write(atob(tempvar));

如果要编码,请改用btoa函数,

var tempvar = "hello";
document.write(btoa(tempvar));

你可以用这个网站来测试base64的解码和编码,https://www.base64encode.org/

这是因为您正在尝试解码一个非 base64 编码的字符串 它在 hi 上有效似乎只是巧合。

atob = 解码

btoa = 编码

您使用了错误的功能。您应该使用 btoa() 进行编码。

当您执行 atob('hi') 时,您实际上是在解码 'hi',它恰好是有效的 base-64。

你的问题

What am I doing wrong?

传递给 atob() 的字符串是长度为 5 的字符串文字(技术上不是 base-64 编码的字符串)。浏览器控制台应在错误日志中显示异常(请参阅下面的 原因 中的解释)。

原因

根据 atob() 的 MDN 文档:

Throws

Throws a DOMException if the length of passed-in string is not a multiple of 4. 1

字符串文字“hello”(即5)的长度不是4的倍数,因此抛出异常而不是返回字符串文字的解码版本。

一个解决方案

一种解决方案是使用实际编码过的字符串(例如 btoa()) or at least has a length of four (e.g. using String.prototype.substring())。有关示例,请参见下面的代码段。

var tempvar = "hello";
window.addEventListener("DOMContentLoaded", function(readyEvent) {
    var container = document.getElementById("container");
    //encode the string
    var encoded = btoa(tempvar); 
    container.innerHTML = encoded;

    var container2 = document.getElementById("container2"); 
    //decode the encoded string
    container2.innerHTML = atob(encoded);  
    
    var container3 = document.getElementById("container3");
    //decode the first 4 characters of the string
    container3.innerHTML = atob(tempvar.substring(0, 4));
});
<div> btoa(tempvar): <span id="container"></span></div> 
<div> atob(decoded): <span id="container2"></span></div>
<div> atob(tempvar.substring(0, 4)): <span id="container3"></span></div> 


1https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/atob