0
# Browser Compatibility Functions
1
2
Low-level functions that replicate browser btoa/atob behavior with cross-platform support and polyfills for environments lacking native implementations.
3
4
## Capabilities
5
6
### Base64 to Binary String (atob)
7
8
Browser-compatible atob function that decodes Base64 to binary string format.
9
10
```typescript { .api }
11
/**
12
* Does what window.atob of web browsers do - converts Base64 to binary string
13
* @param asc - Base64-encoded string
14
* @returns Binary string (each character represents a byte value 0-255)
15
*/
16
function atob(asc: string): string;
17
```
18
19
**Usage Examples:**
20
21
```typescript
22
import { atob } from "js-base64";
23
24
// Basic usage - same as browser's window.atob
25
const binaryString = atob("SGVsbG8="); // "Hello" in Base64
26
console.log(binaryString); // Binary string representation
27
28
// Converting to byte values
29
const bytes = Array.from(binaryString).map(char => char.charCodeAt(0));
30
console.log(bytes); // [72, 101, 108, 108, 111] - ASCII values for "Hello"
31
32
// Working with binary data (like images)
33
const pngHeaderB64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";
34
const binaryData = atob(pngHeaderB64);
35
// binaryData contains the raw PNG bytes as a binary string
36
37
// Note: For UTF-8 text, use decode() instead of atob()
38
// atob("5bCP6aO85by+") will NOT correctly decode Japanese text
39
```
40
41
### Binary String to Base64 (btoa)
42
43
Browser-compatible btoa function that encodes binary string to Base64.
44
45
```typescript { .api }
46
/**
47
* Does what window.btoa of web browsers do - converts binary string to Base64
48
* @param bin - Binary string (each character must have charCode 0-255)
49
* @returns Base64-encoded string
50
*/
51
function btoa(bin: string): string;
52
```
53
54
**Usage Examples:**
55
56
```typescript
57
import { btoa } from "js-base64";
58
59
// Basic usage - same as browser's window.btoa
60
const encoded = btoa("Hello");
61
console.log(encoded); // "SGVsbG8="
62
63
// Creating binary string from byte array
64
const bytes = [72, 101, 108, 108, 111]; // ASCII for "Hello"
65
const binaryString = String.fromCharCode(...bytes);
66
const result = btoa(binaryString);
67
console.log(result); // "SGVsbG8="
68
69
// Working with image data or file bytes
70
const imageBytes = [137, 80, 78, 71, 13, 10, 26, 10]; // PNG header bytes
71
const imageBinaryString = String.fromCharCode(...imageBytes);
72
const imageB64 = btoa(imageBinaryString);
73
console.log(imageB64); // "iVBORw0KGgo="
74
75
// IMPORTANT: Only works with binary strings (characters 0-255)
76
// btoa("小飼弾") will throw TypeError - use encode() for UTF-8 text
77
```
78
79
### Pure JavaScript Polyfills
80
81
Polyfill implementations that work in any JavaScript environment.
82
83
```typescript { .api }
84
/**
85
* Pure JavaScript polyfill version of atob
86
* @param asc - Base64-encoded string
87
* @returns Binary string
88
* @throws TypeError if input is malformed Base64
89
*/
90
function atobPolyfill(asc: string): string;
91
92
/**
93
* Pure JavaScript polyfill version of btoa
94
* @param bin - Binary string (each character must have charCode 0-255)
95
* @returns Base64-encoded string
96
* @throws TypeError if input contains invalid characters (charCode > 255)
97
*/
98
function btoaPolyfill(bin: string): string;
99
```
100
101
**Usage Examples:**
102
103
```typescript
104
import { atobPolyfill, btoaPolyfill } from "js-base64";
105
106
// Use polyfills explicitly (useful for testing or consistent behavior)
107
const encoded = btoaPolyfill("Hello");
108
console.log(encoded); // "SGVsbG8="
109
110
const decoded = atobPolyfill(encoded);
111
console.log(decoded); // "Hello"
112
113
// Error handling
114
try {
115
btoaPolyfill("Hello 🌍"); // Contains character > 255
116
} catch (error) {
117
console.log(error.message); // "invalid character found"
118
}
119
120
try {
121
atobPolyfill("invalid base64!!!");
122
} catch (error) {
123
console.log(error.message); // "malformed base64."
124
}
125
```
126
127
## Key Differences from UTF-8 Functions
128
129
### When to Use atob/btoa vs decode/encode
130
131
```typescript
132
import { atob, btoa, decode, encode } from "js-base64";
133
134
// For UTF-8 text - USE decode/encode
135
const utf8Text = "小飼弾";
136
const utf8Correct = encode(utf8Text); // ✅ Correct: "5bCP6aO85by+"
137
const utf8Decoded = decode(utf8Correct); // ✅ Correct: "小飼弾"
138
139
// DON'T use btoa/atob for UTF-8 text
140
// btoa(utf8Text) // ❌ Throws TypeError
141
142
// For binary data - USE atob/btoa or toUint8Array/fromUint8Array
143
const binaryString = String.fromCharCode(72, 101, 108, 108, 111);
144
const binaryEncoded = btoa(binaryString); // ✅ Correct for binary data
145
const binaryDecoded = atob(binaryEncoded); // ✅ Correct for binary data
146
147
// For image/file data - prefer Uint8Array functions
148
const bytes = new Uint8Array([72, 101, 108, 108, 111]);
149
const fromUint8 = fromUint8Array(bytes); // ✅ Preferred for binary data
150
const toUint8 = toUint8Array(fromUint8); // ✅ Preferred for binary data
151
```
152
153
## Cross-Platform Behavior
154
155
The library automatically chooses the best implementation:
156
157
- **Browser with native btoa/atob**: Uses native functions
158
- **Node.js with Buffer**: Uses Buffer-based implementation
159
- **Other environments**: Uses pure JavaScript polyfills
160
161
```typescript
162
// The library handles environment detection automatically
163
import { atob, btoa } from "js-base64";
164
165
// These work the same everywhere:
166
const encoded = btoa("Hello");
167
const decoded = atob(encoded);
168
```
169
170
## Error Handling
171
172
```typescript
173
import { atob, btoa, atobPolyfill, btoaPolyfill } from "js-base64";
174
175
// btoa/btoaPolyfill errors
176
try {
177
btoa("Text with emoji 🚀"); // Character code > 255
178
} catch (error) {
179
console.log(error instanceof TypeError); // true
180
console.log(error.message); // "invalid character found"
181
}
182
183
// atob/atobPolyfill errors
184
try {
185
atob("Not base64!!!"); // Invalid Base64
186
} catch (error) {
187
console.log(error instanceof TypeError); // true
188
console.log(error.message); // "malformed base64."
189
}
190
```
191
192
## Key Features
193
194
- **Browser Compatibility**: Exact same behavior as native browser functions
195
- **Cross-platform**: Works in Node.js and browsers without native support
196
- **Error Compatibility**: Throws same TypeError types as native functions
197
- **Performance**: Uses native implementations when available
198
- **Polyfill Safety**: Pure JavaScript fallbacks for any environment