Phương thức window.btoa() mã hóa một chuỗi dữ liệu thành chuỗi base-64. Chuỗi này có thể được giải mã bằng phương thức atob().
Cú pháp
window.btoa(chuỗi_cần_mã_hóa);
Ví dụ
Ví dụ minh họa mã hóa và giải mã base-64:
<!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.btoa() / atob()</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 (btoa)</button>
<button onclick="decode()" class="btn">Giải mã (atob)</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 thông điệp vào ô văn bản.
- Nhấn "Mã hóa (btoa)" → hiển thị chuỗi base-64.
- Nhấn "Giải mã (atob)" → khôi phục chuỗi gốc.
Lưu ý: btoa() chỉ hoạt động với chuỗi ASCII. Với Unicode, cần dùng TextEncoder hoặc thư viện.