Search code examples
python-3.xchromium-embeddedflask-socketio

How to initiate an action from one window and perform action in another window in pywebview/eel?


So, I have opened windows in pywebview at a time. Now from window 1, I want to click a button and show some texts in window 2. How can communicate between them? I was thinking of using flask-socketio or any socket based solution. But that seems like overkill for this, is it? How can this be easily achieved?

This is the code to open multiple windows in pywebview:

import webview

if __name__ == '__main__':
    master_window = webview.create_window(title='Window #1', url="<h1>First window</h1>")
    second_window = webview.create_window('Window #2', html='<h1>Second window</h1>')
    webview.start()

Solution

  • Well, in the end, I had to go with the hard way (though it was easy), the socket way. I used flask-socketio to implement this feature. Here is an example:

    Suppose I have 2 separate windows, Window_1, and Window_2. Now I have a button in Window_1, from where I will click a button and a pop-up will show in Window_2.

    Window_1.html

    <button id="click_me" type="button">Click Me</>
    <script>
       // add jquery scripts (use a cdn or download from the source)
       let socket = io.connect('/');
       socket.emit('emit_button_click_signal', {});
    </script>
    

    Window_1.py

    from flask_socketio import SocketIO
    
    app = Flask(__name__)
    socket_io = SocketIO(app, cors_allowed_origins='*')
    
    @socket_io.on('emit_button_click_signal')
    def emit_button_click_signal(data):
        emit('emit_button_click_signal_to_window_2', {}, namespace='/', broadcast=True) # refer to flask-socketio basics for more
    

    Window_2.html

    <script>
        let socket = io.connect('/');
        socket.on('emit_button_click_signal_to_window_2', function (data) {
                // trigger some jquery to show a pop up in HTML..
            });
    </script>
    

    We send a signal to window_2.html (JS is emitting) from window_1.html (JS is receiving) via Window_2.py (which acts as the messenger in OS level). That's it. You can use it to build multi-panel based softwares like photoshop, AutoCAD, Solidworks, etc.