0
# Browser Integration
1
2
Python interface to HTML DOM elements, events, and browser APIs with Pythonic syntax and full browser functionality access. This module provides the core bridge between Python code and the browser environment.
3
4
## Capabilities
5
6
### Core Browser Objects
7
8
Access to fundamental browser objects through Python interfaces.
9
10
```python { .api }
11
# Main browser namespace
12
browser.document: DOMDocument # HTML document interface
13
browser.window: BrowserWindow # Global window object
14
browser.console: Console # Browser console for logging
15
browser.self: Any # Current execution context (window/worker)
16
browser.scope: dict # Global Python scope
17
```
18
19
**Usage:**
20
```python
21
from browser import document, window, console
22
23
# DOM access
24
element = document["element-id"]
25
console.log("Hello from Python!")
26
27
# Window properties
28
current_url = window.location.href
29
```
30
31
### Event Binding
32
33
Decorator-based event handling system for DOM elements and browser events.
34
35
```python { .api }
36
def bind(element: Element, event: str, options: dict = None) -> Callable:
37
"""
38
Event binding decorator for DOM elements.
39
40
Args:
41
element: Target DOM element or selector
42
event: Event type ('click', 'input', 'keydown', etc.)
43
options: Event listener options (capture, once, passive)
44
45
Returns:
46
Decorator function for event handler
47
48
The decorated function receives the event object as its parameter.
49
"""
50
```
51
52
**Usage:**
53
```python
54
from browser import document, bind
55
56
@bind(document["my-button"], "click")
57
def handle_click(event):
58
event.preventDefault()
59
print("Button clicked!")
60
61
@bind(window, "resize")
62
def handle_resize(event):
63
print(f"Window resized: {window.innerWidth}x{window.innerHeight}")
64
65
# Event options
66
@bind(document["form"], "submit", {"once": True})
67
def handle_submit(event):
68
event.preventDefault()
69
# Handle form submission once
70
```
71
72
### Object Storage
73
74
JSON-serialized object storage wrapper for localStorage and sessionStorage.
75
76
```python { .api }
77
class ObjectStorage:
78
"""Dict-like interface for complex object storage with JSON serialization."""
79
80
def __init__(self, storage: Storage):
81
"""
82
Initialize with underlying storage (localStorage/sessionStorage).
83
84
Args:
85
storage: Browser storage object
86
"""
87
88
def __getitem__(self, key: Any) -> Any: ...
89
def __setitem__(self, key: Any, value: Any) -> None: ...
90
def __delitem__(self, key: Any) -> None: ...
91
def __contains__(self, key: Any) -> bool: ...
92
93
def get(self, key: Any, default: Any = None) -> Any: ...
94
def pop(self, key: Any, default: Any = None) -> Any: ...
95
def keys(self) -> list: ...
96
def values(self) -> list: ...
97
def items(self) -> list: ...
98
def clear(self) -> None: ...
99
def __len__(self) -> int: ...
100
```
101
102
**Usage:**
103
```python
104
from browser import window
105
from browser.object_storage import ObjectStorage
106
107
# Create object storage wrapper
108
obj_storage = ObjectStorage(window.localStorage)
109
110
# Store complex objects
111
obj_storage["user"] = {"name": "John", "preferences": {"theme": "dark"}}
112
obj_storage[42] = ["list", "of", "items"]
113
114
# Retrieve objects
115
user = obj_storage["user"] # Returns dict
116
items = obj_storage.get(42, []) # Returns list
117
```
118
119
## Browser Object Types
120
121
```python { .api }
122
class DOMDocument:
123
"""HTML document interface."""
124
def __getitem__(self, id: str) -> Element: ...
125
def createElement(self, tag: str) -> Element: ...
126
def createTextNode(self, text: str) -> TextNode: ...
127
def querySelector(self, selector: str) -> Element: ...
128
def querySelectorAll(self, selector: str) -> list[Element]: ...
129
130
# Properties
131
body: Element
132
head: Element
133
title: str
134
135
class BrowserWindow:
136
"""Global window object."""
137
# Location and navigation
138
location: Location
139
history: History
140
141
# Storage
142
localStorage: Storage
143
sessionStorage: Storage
144
145
# Dimensions
146
innerWidth: int
147
innerHeight: int
148
149
# Methods
150
def alert(self, message: str) -> None: ...
151
def confirm(self, message: str) -> bool: ...
152
def prompt(self, message: str, default: str = "") -> str: ...
153
154
class Console:
155
"""Browser console interface."""
156
def log(self, *args) -> None: ...
157
def error(self, *args) -> None: ...
158
def warn(self, *args) -> None: ...
159
def info(self, *args) -> None: ...
160
def clear(self) -> None: ...
161
162
class Event:
163
"""Browser event object."""
164
target: Element # Event target element
165
currentTarget: Element # Current event handler element
166
type: str # Event type
167
168
def preventDefault(self) -> None: ...
169
def stopPropagation(self) -> None: ...
170
def stopImmediatePropagation(self) -> None: ...
171
```
172
173
## Event Handling Patterns
174
175
### Multiple Event Types
176
177
```python
178
@bind(element, "mouseenter mouseleave")
179
def handle_hover(event):
180
if event.type == "mouseenter":
181
element.style.backgroundColor = "yellow"
182
else:
183
element.style.backgroundColor = ""
184
```
185
186
### Event Delegation
187
188
```python
189
@bind(document, "click")
190
def handle_clicks(event):
191
if event.target.classList.contains("button"):
192
handle_button_click(event)
193
```
194
195
### Custom Event Options
196
197
```python
198
@bind(element, "touchstart", {"passive": True})
199
def handle_touch(event):
200
# Passive listener for better performance
201
pass
202
203
@bind(element, "click", {"once": True, "capture": True})
204
def handle_once(event):
205
# Handle event once in capture phase
206
pass
207
```
208
209
### Template Engine
210
211
HTML templating system with Python code blocks, expressions, and event binding.
212
213
```python { .api }
214
class Template:
215
"""HTML template engine with Python integration."""
216
217
def __init__(self, element: Element | str, callbacks: list[Callable] = None):
218
"""
219
Initialize template for element.
220
221
Args:
222
element: DOM element or element ID string
223
callbacks: List of callback functions for b-on event binding
224
"""
225
226
def render(self, **kwargs) -> None:
227
"""
228
Render template with data values.
229
230
Args:
231
**kwargs: Template variables as keyword arguments
232
"""
233
234
def on(self, element: Element, event: str, callback: Callable) -> None:
235
"""
236
Bind event handler with automatic re-rendering on data changes.
237
238
Args:
239
element: Target element
240
event: Event type
241
callback: Handler function(event, template)
242
"""
243
244
class ElementData:
245
"""Template data object with attribute access."""
246
247
def to_dict(self) -> dict: ...
248
def clone(self) -> dict: ...
249
250
class TemplateError(Exception):
251
"""Template processing errors."""
252
```
253
254
**Template Syntax:**
255
256
```html
257
<!-- Python code blocks -->
258
<tr b-code="for item in items">
259
<td>{item.name}</td>
260
<td>{item.value}</td>
261
</tr>
262
263
<!-- Conditional rendering -->
264
<div b-code="if show_details">
265
<p>Details: {description}</p>
266
</div>
267
268
<!-- Dynamic attributes -->
269
<option value="{name}" selected="{name == selected}">
270
{display_name}
271
</option>
272
273
<!-- Event binding -->
274
<button b-on="click:increment">Count: {counter}</button>
275
276
<!-- Include sub-templates -->
277
<div b-include="menu.html"></div>
278
```
279
280
**Usage:**
281
282
```python
283
from browser import document
284
from browser.template import Template
285
286
def increment(event, template):
287
template.data.counter += 1
288
289
def decrement(event, template):
290
template.data.counter -= 1
291
292
# Create template with callbacks
293
template = Template(document["app"], [increment, decrement])
294
295
# Render with initial data
296
template.render(
297
counter=0,
298
items=[{"name": "Item 1", "value": 10}],
299
show_details=True,
300
selected="option1"
301
)
302
```
303
304
This browser integration layer provides the foundation for all Brython web development, enabling Python code to interact naturally with browser APIs and DOM elements.