Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reload/Refresh a webpage using pywebview library in python

It is possible to make a web page reload using the pywebview library? I mean, I have this code:

import webview

webview.create_window('Woah dude!', 'index.html')
webview.start(http_server=True)

…and I want to reload the web page every five seconds because changes are being made in the HTML file.

like image 619
Asibusa Avatar asked Jun 18 '26 16:06

Asibusa


1 Answers

I'm a bit late to the party, but my method is a bit different compared to the other solution. You can use Watchfiles which detects changes to your directory.

import watchfiles

def watch_and_reload(window):
    for change in watchfiles.watch('directory/to/watch'):
        ## i couldn't get window.load_url() to actually work so I used this instead
        window.evaluate_js('window.location.reload()')

if __name__ == '__main__':
    window = webview.create_window('Application', path)

    ## pass the watch function to the start method
    webview.start(watch_and_reload, window, http_server=True)

Though this doesn't terminate the watcher which requires you to kill the process yourself. Here is a version that automatically terminates the process:

import webview, watchfiles, threading

def watch_and_reload(window, event):
    for change in watchfiles.watch('file/or/folder/to/watch', stop_event=event):
        ## using this instead of window.load_url() because that didn't work for me
        window.evaluate_js('window.location.reload()')

if __name__ == '__main__':
    window = webview.create_window(
            title = 'Application',
            url = 'path/to/html',
        )
    
    ## this handles stopping the watcher
    thread_running = threading.Event()
    thread_running.set()

    ## using a thread to watch
    reload_thread = threading.Thread(
            target = watch_and_reload,
            args = (window, thread_running)
        )
    reload_thread.start()
    
    ## start the webview app
    webview.start(window, debug=True)

    ## upon the webview app exitting, stop the watcher
    thread_running.clear()
    reload_thread.join()

    print('exitted successfully!')
like image 169
Maverick Lally Avatar answered Jun 21 '26 06:06

Maverick Lally