3

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.

2 Answers 2

4

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!')
Sign up to request clarification or add additional context in comments.

Comments

2

Try to do this:

import webview
import time

def reload(window):
    while True:
        time.sleep(5)
        window.load_url('index.html')
        
        
if __name__ == '__main__':
    window = webview.create_window('hello', 'index.html')

    webview.start(reload, window, http_server=True)

        

This will 'reload'the page each 5 seconds. It's not really reloading it, it is basically loading the same url, so it should work.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.