脚本之前的javafx WebView setMember() [英] javafx WebView setMember() before script

查看:135
本文介绍了脚本之前的javafx WebView setMember()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在页面上设置一些javascript项目,但是在页面上运行javascript之后,这些项目会被设置.因此,例如,我创建了一个Console.log()方法以在Java控制台中显示内容以进行调试.但是,在页面代码运行之后,各项已设置完毕,因此日志记录不起作用(请参阅第二段代码).在页面上的javascript运行之前,有没有办法让我初始化代码?

I am trying to set some javascript items on my page, but the items are getting set after the javascript runs on the page. So for example, I created a Console.log() method to display stuff in my java console for debugging purposes. But the items are getting set after the page code runs so the logging doesn't work (See second block of code). Is there a way for me to initiate the code before the javascript on the page runs?

因此,这是我如何在Java应用程序中启动该项目的方法:

So, here is how I am initiating the item in my Java application:

webEngine.getLoadWorker().stateProperty().addListener(new ChangeListener<Worker.State>(){
    if(newState.equals(Worker.State.SUCCEEDED)){
        JSObject win = (JSObject)Browser.webEngine.executeScript("window");
        win.setMember("$js", new JavaScriptBinder());
        win.setMember("console", new JSConsole());
    }
}

这是一个JavaScript示例:

Here is a javascript example:

<script>
    // This line doesn't work:
    console.log("Hello");

    element.addEventListener("click", function(){
        // This line does work:
        console.log("Hello from a click");
    });
</script>

推荐答案

在运行JavaScript代码之前,请不要让页面完成加载.考虑将您的代码链接到window.onload方法,例如

You aren't letting the page finish loading before you run your javascript code. Consider linking your code to the window.onload method, e.g.

<script>
   function startup() {
      alert("The page has finished loading!  I'm ready to do stuff!");  
   }
   window.onload=startup;
</script>

当然,如果代码的任何其他部分也尝试将自身附加到window.onload,则可能会导致问题. 如果您是这种情况,我建议您阅读这篇文章. FWIW,我也阅读了代码示例该页面上方.

Of course, this could cause a problem if any other parts of your code also try to attach themselves to window.onload. I recommend reading this article if this is the case for you. FWIW, I also took the code sample above from that page.

这篇关于脚本之前的javafx WebView setMember()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆