javascriptjavajxbrowser

How can I inject JavaScript code to periodically refresh a page


I have a plain HTML file that I would like to calls via JxBrowser (backend Java).

JxBrowser allows you to add JavaScript code via:

// Java code 
Browser browser = new Browser(...);
browser.loadURL(...);
...
String test = "setTimeout(function() { alert('hello'); location.reload();}, 6000)";
browser.executeJavaScript(test);

This code will indeed refresh the page, but only once because when the html page is refreshed, whatever was added by JxBrowser seems to be cleared.

Without modifying the html file (or the front end), is it possible to add a script such that this page can be continuously refreshed every 6 seconds?

The only other way I can think of is to periodically execute browser.executeJavaScript(test).

1. create a new nonblocking thread
2. for every 6 seconds, call browser.executeJavaScript(test)

Thank you.


Solution

  • Why reloading web page from JavaScript? Why not doing it from Java code instead? For example:

    Browser browser = engine.newBrowser();
    Navigation navigation = browser.navigation();
    navigation.loadUrl("https://www.google.com");
    new java.util.Timer().schedule(new TimerTask() {
        @Override
        public void run() {
            navigation.reload();
        }
    }, 1_000, 60_000);