JxBrowser onStartLoadingFrame Data Passing Issue

I am currently using JxBrowser 6.19.1 and I would like to ask if it is possible to set a variable value when I first start loading a page, by using onStartLoadingFrame. Then I am going to use that data in the page.

For example:

    final JFrame frame = new JFrame("Hello World!");

    final Browser browser = new Browser();
    BrowserView view = new BrowserView(browser);

    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.add(view, BorderLayout.CENTER);
    frame.setSize(400, 300);
    frame.setVisible(true);

    browser.addLoadListener(new LoadAdapter() {
        @Override
        public void onStartLoadingFrame(StartLoadingEvent event) {
            browser.executeJavaScriptAndReturnValue("var data = 1"); // does not work every single time, real question
        }
    });
    browser.loadURL("echo.html");

where my echo.html will be something like this:

 <!DOCTYPE html>
 <html lang="en">
 <head>
    <title>Document</title>
 </head>
 <body>
     <h1>Echo Page</h1>
     <script>
         alert(data); 
     </script>
 </body>

The question comes, sometimes it prompt the alert, sometimes doesn't. Does anyone know why? (Due to Multitheading?) Is that any work around for this?

Hope someone can help me with that. Thanks.

1 answer

  • answered 2018-05-16 14:09 Anna Dolbina

    If you need to execute some JavaScript code before any other JavaScript on the loaded web page is executed, then you should use the onScriptContextCreated JavaScript context event as shown below:

    browser.addScriptContextListener(new ScriptContextAdapter() {
        @Override
        public void onScriptContextCreated(ScriptContextEvent event) {
            event.getBrowser().executeJavaScript("var data = 1"); 
        }
    });
    

    In this case, the data JavaScript variable will be set properly, and the script on the web page will always work as expected.