Phương thức window.atob() giải mã một chuỗi base-64 đã được mã hóa bởi btoa() trở lại chuỗi gốc.
Cú pháp
window.atob(chuỗi_base64);
Ví dụ
Ví dụ đầy đủ mã hóa/giải mã (giống ví dụ btoa):
<!DOCTYPE html>
<html>
<style>
body {
color: #000;
height: 100vh;
background: linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%) no-repeat;
text-align: center;
}
.btn {
background: #db133a;
border: none;
height: 2rem;
border-radius: 2px;
width: 40%;
display: block;
color: #fff;
outline: none;
cursor: pointer;
margin: 1rem auto;
}
::placeholder { color: #000; }
</style>
<body>
<h1>Demo window.atob() / btoa()</h1>
<textarea placeholder="Nhập thông điệp tại đây" cols="30" rows="5"></textarea>
<button onclick="encode()" class="btn">Mã hóa</button>
<button onclick="decode()" class="btn">Giải mã</button>
<div class="show"></div>
<script>
var show = document.querySelector(".show");
function encode() {
var encMsg = window.btoa(document.querySelector("textarea").value);
show.innerHTML = encMsg;
}
function decode() {
var decMsg = window.atob(document.querySelector("textarea").value);
show.innerHTML = decMsg;
}
</script>
</body>
</html>
Kết quả
Nhập chuỗi base-64 hợp lệ vào ô văn bản, nhấn "Giải mã" để xem nội dung gốc.
Lưu ý: Nếu chuỗi không phải base-64 hợp lệ, atob() sẽ ném lỗi DOMException.