Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

State sharing between Python and Javascript #1594

Open
r0x0r opened this issue Feb 6, 2025 · 1 comment
Open

State sharing between Python and Javascript #1594

r0x0r opened this issue Feb 6, 2025 · 1 comment

Comments

@r0x0r
Copy link
Owner

r0x0r commented Feb 6, 2025

The next major version of pywebview will introduce state - a way to seamlessly share data between Python and Javascript. State is represented by the pywebview.state object in Javascript and Window.state object in Python. Updating a property on either object will update its value on the other side. An example can be found here.

Additionally, each state object emits an event when state is updated. Implementation details are not set in stone, but currently the syntax is pywebview.state.addEventHandler('change', handler) and window.state += lambda event_type, key, value: pass

State is implemented by means of a proxy in Javascript and an observable class in Python.

The current ahem state can be tracked in the store branch

Ideas, suggestions or questions are welcomed

@r0x0r
Copy link
Owner Author

r0x0r commented Mar 2, 2025

As far as I am concerned, basic implementation is done now. Latest changes are pushed into the 6.0 branch.

One limitation of the current version is that it detects changes only on the window.state object itself and mutations of the objects are not registered. Ie this will trigger a state update window.state.counter = 1 and this will not

window.state.nested_counter = {
   'counter': 0
}
window.state.nested_counter['counter'] = 1 # this goes undetected

I have attempted to solve this with two different approaches

  1. By converting dicts and lists to observable versions, which detect and propagate changes. The implementation turned out rather complicated and I could not get it fully working. Besides I am not exactly sure if it is a good approach to convert user data be default
  2. By making State object assignable and introducing sub-states. Something like this
sub_state = State({'counter': 0})
window.state.nested_counter = sub_state
sub_state.counter = 1 # this will be detected

Sub-states have exactly same API as the main state

Anyhow neither of these approaches are implemented, nor will be for the 6.0. It remains to be seen if this feature is needed.

Another feature that might be introduced in the future is global state, a state object which can be shared between different windows.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant