问题
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?
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());
}
}
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>
回答1:
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>
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.
来源:https://stackoverflow.com/questions/23687127/javafx-webview-setmember-before-script