IntroductionInstallationLimitations of the "file" protocolFrequently asked questionsSyntax, keywords and built-in functionsStandard distributionimport implementationBrython packagesBrowser interface
Introduction - DOM API
Creating a document Accessing elements Attributes, properties and methods Events Mouse events Keyboard events Focus events Drag events Query string Interactions with Javascript Brython-specific built-in modules
browser
browser.aio browser.ajax browser.html browser.local_storage browser.markdown browser.object_storage browser.session_storage browser.svg browser.template browser.timer browser.webcomponent browser.websocket browser.worker Widgets browser.widgets.dialog browser.widgets.menu interpreter javascript Working with BrythonCookbook |
module browser.workerThe module worker is an implementation of WebWorkers for Brython. A "worker" is a Python script that receives messages from the main script, and sends back messages in reply. The worker is executed in a different thread from the main script; even if it takes a long time to complete, the main script remains responsive and the browser doesn't freeze. The main script and the worker communicate by messages. A message must be a "simple" Python object (string, number, list with "simple" items, dictionary with "simple" keys and values). A worker has a restricted access to the browser features ; for instance it can't access the document currently displayed, nor modify it.Inserting a worker script in an HTML pageA worker script is inserted in an HTML page with a specific form of the<script type="text/python"> tag:
<script type="text/python" class="webworker" id="myworker"> # instructions of the worker program </script>The attribute src can also be used to load the worker script:
<script type="text/python" class="webworker" id="myworker" src="myworker.py"> </script>Adding the "webworker" class specifies that the script must not be executed as an ordinary Python script, but that it is intended to be used as a worker by a main script. The attribute id is mandatory (an AttributeError is raised otherwise) ; it
is used by the main script as a reference to the worker script.
Using a worker from the main scriptThe main script creates a worker object with the functioncreate_worker:
create_worker(worker_id, onready=None, onmessage=None, onerror=None)
triggers the creation of a worker object, based on the script referenced by the identifier worker_id (the attributeThe worker object has a method send(message)
sends a message to the worker How a worker worksIn a worker, the browser module doesn't have all the usual attributes, for instance not those that allow access to the document: for instance thedocument attribute or the html module are not available.
The window attribute itself is not defined; instead, an attribute self
represents the worker and manages the relationship with the main script it is
associated with.
This object browser.self has 2 methods:
bind(evt, function)
binds the function to the event evt. The main event is "message" : it is triggered when the main script sends a message to the worker.
The function takes a single parameter, an event object with the attribute
Also note that instead of binding the event by the syntax
you can use the function
send(message)
sends a message to the main script ExampleThe gallery provides an example of a Web Worker written with Brython. Code of the main script:"""Main script."""
from browser import bind, document, worker
result = document.select_one('.result')
inputs = document.select("input")
def onmessage(e):
"""Handles the messages sent by the worker."""
result.text = e.data
def onready(myWorker):
@bind(inputs, "change")
def change(evt):
"""Called when the value in one of the input fields changes."""
# Send a message (here a list of values) to the worker
myWorker.send([x.value for x in inputs])
# Create a web worker, identified by a script id in this page.
worker.create_worker("worker", onready, onmessage)
Code of the worker script:
"""Web Worker script."""
# In web workers, "window" is replaced by "self".
from browser import bind, self
@bind(self, "message")
def message(evt):
"""Handle a message sent by the main script.
evt.data is the message body.
"""
try:
result = int(evt.data[0]) * int(evt.data[1])
workerResult = f'Result: {result}'
# Send a message to the main script.
# In the main script, it will be handled by the function passed as the
# argument "onmessage" of create_worker().
self.send(workerResult)
except ValueError:
self.send('Please write two numbers')
The Worker class (deprecated in version 3.12)For backwards compatibility, the module exposes a deprecated class to create a worker in the main scriptWorker(worker_id)
creates a worker object, based on the script referenced by the identifier
worker_id (the attribute
This version is not asynchronous.
The instances of the Worker class have 2 methods:
bind(evt, function)
binds the function to the event evt. The main event is "message" : it is triggered when the worker sends a message to the main script.
The function takes a single parameter, an event object with the attribute
Also note that instead of binding the event by the syntax
you can use the function
send(message)
sends a message to the worker |