0
# Browser Integration
1
2
**IMPORTANT**: The browser APIs in `kotlin.browser` package are deprecated since Kotlin 1.4 and will be removed in future versions. For modern browser integration, use the `kotlinx.browser` library instead.
3
4
This documentation describes the deprecated browser APIs that are still present in kotlin-stdlib-js for compatibility.
5
6
## Capabilities
7
8
### Deprecated Browser Global Objects
9
10
**⚠️ DEPRECATED**: These APIs are deprecated since Kotlin 1.4. Use `kotlinx.browser` instead.
11
12
```kotlin { .api }
13
/**
14
* Browser window object
15
* @deprecated Use kotlinx.browser.window instead
16
*/
17
@Deprecated("Use kotlinx.browser.window instead", ReplaceWith("window", "kotlinx.browser.window"))
18
external val window: Window
19
20
/**
21
* HTML document object
22
* @deprecated Use kotlinx.browser.document instead
23
*/
24
@Deprecated("Use kotlinx.browser.document instead", ReplaceWith("document", "kotlinx.browser.document"))
25
external val document: Document
26
27
/**
28
* Local storage for persistent data
29
* @deprecated Use kotlinx.browser.localStorage instead
30
*/
31
@Deprecated("Use kotlinx.browser.localStorage instead", ReplaceWith("localStorage", "kotlinx.browser.localStorage"))
32
external val localStorage: Storage
33
34
/**
35
* Session storage for temporary data
36
* @deprecated Use kotlinx.browser.sessionStorage instead
37
*/
38
@Deprecated("Use kotlinx.browser.sessionStorage instead", ReplaceWith("sessionStorage", "kotlinx.browser.sessionStorage"))
39
external val sessionStorage: Storage
40
```
41
42
**Usage Examples:**
43
44
```kotlin
45
import kotlinx.browser.*
46
47
// Access browser globals
48
console.log("Page loaded!")
49
console.error("Error occurred")
50
51
// Document manipulation
52
val title = document.title
53
document.title = "My Kotlin/JS App"
54
55
// Local storage
56
localStorage.setItem("user", "john_doe")
57
val user = localStorage.getItem("user") // "john_doe"
58
localStorage.removeItem("user")
59
60
// Session storage (cleared when tab closes)
61
sessionStorage.setItem("temp_data", "some_value")
62
val tempData = sessionStorage.getItem("temp_data")
63
64
// Window operations
65
window.alert("Hello from Kotlin!")
66
val width = window.innerWidth
67
val height = window.innerHeight
68
69
// Navigation
70
location.href = "https://example.com"
71
history.back()
72
```
73
74
### DOM Element Creation Utilities
75
76
Convenient functions for creating and configuring DOM elements.
77
78
```kotlin { .api }
79
/**
80
* Create HTML element with initialization block
81
*/
82
fun Document.createElement(name: String, init: Element.() -> Unit): Element
83
84
/**
85
* Create specific HTML elements with type safety
86
*/
87
fun Document.createDiv(init: HTMLDivElement.() -> Unit = {}): HTMLDivElement
88
fun Document.createSpan(init: HTMLSpanElement.() -> Unit = {}): HTMLSpanElement
89
fun Document.createInput(init: HTMLInputElement.() -> Unit = {}): HTMLInputElement
90
fun Document.createButton(init: HTMLButtonElement.() -> Unit = {}): HTMLButtonElement
91
fun Document.createImg(init: HTMLImageElement.() -> Unit = {}): HTMLImageElement
92
fun Document.createA(init: HTMLAnchorElement.() -> Unit = {}): HTMLAnchorElement
93
94
/**
95
* Append newly created element to parent
96
*/
97
fun Element.appendElement(name: String, init: Element.() -> Unit): Element
98
99
/**
100
* Append text node to element
101
*/
102
fun Element.appendText(text: String): Text
103
```
104
105
**Usage Examples:**
106
107
```kotlin
108
import kotlinx.browser.*
109
import kotlinx.dom.*
110
import org.w3c.dom.*
111
112
// Create elements with initialization
113
val div = document.createElement("div") {
114
className = "container"
115
id = "main-container"
116
textContent = "Hello, World!"
117
}
118
119
// Type-safe element creation
120
val input = document.createInput {
121
type = "text"
122
placeholder = "Enter your name"
123
value = "Default value"
124
}
125
126
val button = document.createButton {
127
textContent = "Click me"
128
onclick = { event ->
129
console.log("Button clicked!")
130
}
131
}
132
133
// Append to document
134
document.body?.appendChild(div)
135
document.body?.appendChild(input)
136
document.body?.appendChild(button)
137
138
// Chain element creation
139
val container = document.body?.appendElement("div") {
140
className = "wrapper"
141
142
appendElement("h1") {
143
textContent = "Title"
144
}
145
146
appendElement("p") {
147
appendText("This is a paragraph with ")
148
appendElement("strong") {
149
textContent = "bold text"
150
}
151
appendText(".")
152
}
153
}
154
```
155
156
### CSS Class Manipulation
157
158
Utilities for working with CSS classes on DOM elements.
159
160
```kotlin { .api }
161
/**
162
* Check if element has CSS class
163
*/
164
fun Element.hasClass(cssClass: String): Boolean
165
166
/**
167
* Add CSS classes to element
168
*/
169
fun Element.addClass(vararg cssClasses: String)
170
171
/**
172
* Remove CSS classes from element
173
*/
174
fun Element.removeClass(vararg cssClasses: String)
175
176
/**
177
* Toggle CSS class on element
178
*/
179
fun Element.toggleClass(cssClass: String)
180
181
/**
182
* Set CSS classes (replaces all existing classes)
183
*/
184
fun Element.setClasses(vararg cssClasses: String)
185
```
186
187
**Usage Examples:**
188
189
```kotlin
190
import kotlinx.dom.*
191
import org.w3c.dom.*
192
193
val element = document.getElementById("my-element")!!
194
195
// Check for class
196
val hasActive = element.hasClass("active") // true/false
197
198
// Add classes
199
element.addClass("highlight", "important")
200
201
// Remove classes
202
element.removeClass("old-style", "deprecated")
203
204
// Toggle class (add if missing, remove if present)
205
element.toggleClass("expanded")
206
207
// Replace all classes
208
element.setClasses("new-style", "modern", "responsive")
209
210
// Conditional class management
211
if (someCondition) {
212
element.addClass("special")
213
} else {
214
element.removeClass("special")
215
}
216
```
217
218
### DOM Tree Manipulation
219
220
Utilities for manipulating the DOM tree structure.
221
222
```kotlin { .api }
223
/**
224
* Remove all child nodes from element
225
*/
226
fun Node.clear()
227
228
/**
229
* Check if node is text node
230
*/
231
val Node.isText: Boolean
232
233
/**
234
* Check if node is element node
235
*/
236
val Node.isElement: Boolean
237
238
/**
239
* Get all child elements (excluding text nodes)
240
*/
241
val Element.childElements: List<Element>
242
243
/**
244
* Find first child element with matching tag name
245
*/
246
fun Element.firstChildElement(tagName: String): Element?
247
248
/**
249
* Remove element from its parent
250
*/
251
fun Element.remove()
252
```
253
254
**Usage Examples:**
255
256
```kotlin
257
import kotlinx.dom.*
258
import kotlinx.browser.*
259
import org.w3c.dom.*
260
261
val container = document.getElementById("container")!!
262
263
// Clear all content
264
container.clear()
265
266
// Check node types
267
val textNode = document.createTextNode("Hello")
268
val elementNode = document.createElement("div")
269
270
console.log("Text node: ${textNode.isText}") // true
271
console.log("Element node: ${elementNode.isElement}") // true
272
273
// Work with child elements
274
val parent = document.createElement("div") {
275
appendElement("h1") { textContent = "Title" }
276
appendText("Some text")
277
appendElement("p") { textContent = "Paragraph" }
278
}
279
280
val elements = parent.childElements // List of h1 and p elements (no text)
281
val firstH1 = parent.firstChildElement("h1")
282
283
// Remove element
284
val unwantedElement = document.getElementById("unwanted")
285
unwantedElement?.remove()
286
```
287
288
### Storage Utilities
289
290
Enhanced utilities for working with browser storage.
291
292
```kotlin { .api }
293
/**
294
* Storage interface (localStorage/sessionStorage)
295
*/
296
external interface Storage {
297
val length: Int
298
fun key(index: Int): String?
299
fun getItem(keyName: String): String?
300
fun setItem(keyName: String, keyValue: String)
301
fun removeItem(keyName: String)
302
fun clear()
303
}
304
305
/**
306
* Type-safe storage operations
307
*/
308
fun Storage.getBoolean(key: String): Boolean?
309
fun Storage.setBoolean(key: String, value: Boolean)
310
fun Storage.getInt(key: String): Int?
311
fun Storage.setInt(key: String, value: Int)
312
fun Storage.getDouble(key: String): Double?
313
fun Storage.setDouble(key: String, value: Double)
314
315
/**
316
* JSON storage operations
317
*/
318
inline fun <reified T> Storage.getObject(key: String): T?
319
inline fun <reified T> Storage.setObject(key: String, value: T)
320
```
321
322
**Usage Examples:**
323
324
```kotlin
325
import kotlinx.browser.*
326
327
// String storage
328
localStorage.setItem("username", "alice")
329
val username = localStorage.getItem("username") // "alice"
330
331
// Type-safe storage
332
localStorage.setBoolean("isLoggedIn", true)
333
val isLoggedIn = localStorage.getBoolean("isLoggedIn") // true
334
335
localStorage.setInt("score", 1500)
336
val score = localStorage.getInt("score") // 1500
337
338
// JSON object storage
339
data class UserPrefs(val theme: String, val notifications: Boolean)
340
341
val prefs = UserPrefs("dark", true)
342
localStorage.setObject("preferences", prefs)
343
val savedPrefs = localStorage.getObject<UserPrefs>("preferences")
344
345
// Storage management
346
val totalItems = localStorage.length
347
for (i in 0 until totalItems) {
348
val key = localStorage.key(i)
349
console.log("Key: $key")
350
}
351
352
localStorage.clear() // Remove all items
353
```
354
355
## Types
356
357
```kotlin { .api }
358
// Browser global objects
359
external val window: Window
360
external val document: Document
361
external val localStorage: Storage
362
external val sessionStorage: Storage
363
external val console: Console
364
external val location: Location
365
external val history: History
366
external val navigator: Navigator
367
368
// Storage interface
369
external interface Storage {
370
val length: Int
371
fun key(index: Int): String?
372
fun getItem(keyName: String): String?
373
fun setItem(keyName: String, keyValue: String)
374
fun removeItem(keyName: String)
375
fun clear()
376
}
377
378
// Browser API interfaces
379
external interface Window : EventTarget
380
external interface Console {
381
fun log(vararg data: Any?)
382
fun error(vararg data: Any?)
383
fun warn(vararg data: Any?)
384
fun info(vararg data: Any?)
385
}
386
387
external interface Location {
388
var href: String
389
val hostname: String
390
val pathname: String
391
val search: String
392
val hash: String
393
fun reload()
394
}
395
396
external interface History {
397
val length: Int
398
fun back()
399
fun forward()
400
fun go(delta: Int)
401
fun pushState(data: Any?, title: String, url: String?)
402
fun replaceState(data: Any?, title: String, url: String?)
403
}
404
405
external interface Navigator {
406
val userAgent: String
407
val language: String
408
val languages: Array<String>
409
val cookieEnabled: Boolean
410
val onLine: Boolean
411
}
412
413
// DOM utility extensions
414
val Node.isText: Boolean
415
val Node.isElement: Boolean
416
val Element.childElements: List<Element>
417
```