Importing JS Objects in Python
The PyScript (Pyodide) and PyScript(Micropython) version of this recipe are identical,
In PyScript, the object window
in the pyscript
namespace is a proxy for the JavaScript Global Scope of the main thread That is to say, if we have an variable in the JavaScript global scope of the main (window) thread:
<script>
// Create a JavaScript global variable called my_string
var my_string = "Hello, world"
</script>
We can access it (and in this case, print the string it represents) using either any of the following Python syntax options:
orTip
These examples work regardless of whether the code is run in the main thread or a worker thread - pyscript.window
always references the global scope of the main thread. If you need access to the global scope of a worker thread, use import js
, which is a proxy for the global scope of the thread the code is running in.
In Pyodide, the pseudo-module js
is a proxy for the JavaScript Global Scope of the thread the code is currently running in. That is to say, if we have an variable in the JavaScript global scope:
<script>
// Create a JavaScript global variable called my_string
var my_string = "Hello, world"
</script>
We can access it (and in this case, print the string it represents) using either any of the following Python syntax options: