Calling javascript from JavaFX

This is well documented, yet I am having trouble communicating with JavaScript from JavaFX. The relevant snippet is:
WebView wv = new WebView();
WebEngine we = wv.getEngine();
String content = FileUtils.readFileToString(new File("test.html"));
we.loadContent(content);
we.executeScript("changeBackground();");Which reads the following content:
test.html:
<html>
<body>
<script type="text/javascript">
document.bgColor = "#cccccc";
function changeBackground()
  document.bgColor = "#ff0000";
</script>
</body>
</html>giving error:
netscape.javascript.JSException: ReferenceError: Can't find variable: changeBackground
     at com.sun.webpane.platform.WebPage.twkExecuteScript(Native Method)
     at com.sun.webpane.platform.WebPage.executeScript(WebPage.java:1438)
     at javafx.scene.web.WebEngine.executeScript(WebEngine.java:811)
     at com.javainc.tmi.WebTest.init(WebTest.java:30)
     at com.javainc.tmi.WebTest.start(WebTest.java:44)
     at com.sun.javafx.application.LauncherImpl$5.run(LauncherImpl.java:319)
     at com.sun.javafx.application.PlatformImpl$5.run(PlatformImpl.java:206)
     at com.sun.javafx.application.PlatformImpl$4.run(PlatformImpl.java:173)
     at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
     at com.sun.glass.ui.win.WinApplication.access$100(WinApplication.java:29)
     at com.sun.glass.ui.win.WinApplication$3$1.run(WinApplication.java:73)
     at java.lang.Thread.run(Unknown Source)I've tried it without the semi colons at the end as well as every permutation I can think of.
When I remove the executeScript code, the webview displays and turns the screen grey as it should.
Is this a bug or am I missing something obvious?
I am using 64 bit jdk1.7.0_09 on Windows 7.
- Pat

The document loads into the WebEngine asynchronously.
You have to wait for it to finish loading before you try to run a script on it.
For example, you can listen to the document property:
we.documentProperty().addListener(new ChangeListener<Document>() {
  @Override public void changed(ObservableValue<? extends Document> observableValue, Document document, Document newDoc) {
    if (newDoc != null) {
      we.documentProperty().removeListener(this);
      we.executeScript("changeBackground();");
});Or you could grab the WebEngine's LoadWorker and listen for it's state change.
Some shorthand where you provide the load or loadContent method with a CallBack to be executed in the event of a successful page load might be convenient, so you could file a request in jira if you'd like that, but the listener methods work ok too.
Full executable example (using your test.html):
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.Scene;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import org.w3c.dom.Document;
import java.io.*;
public class ScriptExecutive extends Application {
  public static void main(String[] args) { launch(args); }
  @Override public void start(final Stage stage) {
    final WebView wv = new WebView();
    final WebEngine we = wv.getEngine();
    we.documentProperty().addListener(new ChangeListener<Document>() {
      @Override public void changed(ObservableValue<? extends Document> observableValue, Document document, Document newDoc) {
        if (newDoc != null) {
          we.documentProperty().removeListener(this);
          we.executeScript("changeBackground();");
    String content = FileUtils.readFileToString(new File("test.html"));
    we.loadContent(content);
    stage.setScene(new Scene(wv));
    stage.show();
  static class FileUtils {
    public static String readFileToString(File file) {
      try {
        StringBuilder builder = new StringBuilder();
        String line;
        BufferedReader reader = new BufferedReader(new FileReader(file));
        while ((line = reader.readLine()) != null) builder.append(line);
        return builder.toString();
      } catch (FileNotFoundException e) {
        System.out.println("Cannot find: " + file);
        return "";
      } catch (IOException e) {
        System.out.println("Oh snap, it broke: " + e);
        return "";
}

Similar Messages

  • Calling SOAP From JavaFX

    Hi to all,
    Is there any way to Calling SOAP From JavaFX? How?
    Thanks in advance.

    I am not sure about SOAP, but you can use REST-based web services with Javafx.

  • Calling Javascript from JApplet

    Does anyone know of a foolproof way of calling Javascript from an Applet on a Web page. I have heard of the JS Object but can't find much aboout it. Does anyone have any ideas?

    or...
    http://turtle.ee.ncku.edu.tw/~zulu/research/seminor02/
    http://turtle.ee.ncku.edu.tw/~zulu/research/
    JRG

  • Calling javascript from 10g Forms

    Hi,
    RE: How do I call Javascript from Forms 10g (v 10.1.2.0.2)
    Sorry if this post is to the wrong audience but was wondering (as I haven't had an update from the Forms forum) if anyone could tell me how to know
    when a user was navigating away from the current open form because they had entered a new URL in the address bar and were trying to navigate to it?
    The reason for this is that i would want to prompt the user to confirm that they wanted to exit the form as potentially they would have a record (in the form)
    flagged as being updated and as such no other user (including themselves) could susbequently access it.
    So, I'm basically wanting to know if there is a way (by using Javascript?) to catch the fact that the user is about to navigate to another web page.
    Kind regards,
    Tom

    Hi John,
    Well, I'm chasing my tail about this one as not getting any response from any area.
    Apart from the Oracle Forms forum, any other one that you would suggest?
    Kind regards,
    Tom

  • "ReferenceError: "myIpAddr"  is not defined, when call JavaScript from java

    Hi developers,
    My java application was trying to issue a http request via proxy auto-config. So, I did below jobs
    1. Read URL of *.pac from registry
    2. Call FindProxyForURL from java, the code is like below
                   ScriptEngineManager factory = new ScriptEngineManager();
                   ScriptEngine engine = factory.getEngineByName("JavaScript");
                   engine.eval(autoProxyScript);
                   Invocable inv = (Invocable) engine;
                   Object obj = inv.invokeFunction("FindProxyForURL",
                             "http://java.sun.com/",
                             "java.sun.com");
    However, I got "ReferenceError: "myIpAddress" is not defined
    I can not change the script on server to add a function like "myIpAddress", I am wordering why IE or mozilla can call it successfully and get proxy server, while Java failed to do that.
    I got a ugly solution by calling "pacparser" by jni. But I really hope I can get a better solution.

    A .pac file is a JavaScript, but it requires some functions to be defined in the executing context to work (i.e. you must define those).
    From the example on the Wikipedia page there's at least "shExpMatch" and "isInNet". "myIpAddress" seems to be another such candidate.

  • Calling Javascript from ABAP webdynpro application

    Hai All,
    I want to call a Javascript from ABAP-Webdynpro application. If anyone has done this. Please let me know.
    Thanks & Regards,
    H.K.Hayath Basha.

    go to window
    create suspend outbound plug and resume inbound type
    when create an outbound plug of Suspend type a parameter Url is automatically created,
    fire the outbuond plug with the Url to a BSP page where you have JavaScript.
    and fromt he BSP navigate back to WDA again which you can do using by reading the url parameter sap-wd-resumeurl, which contains the WDA URL
    Abhi

  • Calling javascript from a button

    Good morning everyone!
    I need to add a message box that asks the user a confirmation to delete information. So I want my delete button to call the javascript necessary to confirm the delete and then delete.
    My problem is in calling the javascript. I'm able to do so by using an image for my button and in the image attributes add:
    onclick="javascript:confirmDelete('Are you sure you to delete?');"
    This works perfectly, except for one thing: I don't want to use an image for the button. It doesn't fit with the rest of the application.
    I know it can work, because Oracle is using it on this page:
    http://apex.oracle.com/pls/otn/f?p=37719:8:3069181226556730::NO:::
    So how can I call my javascript from an ordinary button?

    I have a related question:
    How can I access the BROWSER_LANGUAGE in javascript? With my method of calling javascript, I didn't find a good way to pass variables to the function that I call.

  • How to call javascript from java application

    How can we call a function written in javascript from java application (core java not applet)? How will java identify javascript?
    Is there any such options ?

    Try creating a page called launcher.html (for example). That does this:
    <html>
    <head>
    <script language="javascript">
    windowHandle=window.open("http://www.javasoft.com", "", "height=700,width=1000,status=no,scrollbars=yes,resizable=yes,toolbar=no,menubar=no,location=no,top=5,left=5");
    </script>
    </head>
    </html>Now you launch IE (or whatever) with this page using the Runtime class. After x seconds (after the second window has been launched) try killing the process. Hopefully it will kill the original window you opened and not the window you popup (the one without toolbars etc)
    It might kill both windows but I can't be bothered to test it. If it does you'll have to try and find a workaround.

  • Calling javascript from subdomain

    I have the swf file on the main domain and I call them from a
    subdomain. All works fine except javascript. Does anybody ahve an
    idea why? The same code that I use on a subdomain I use on the main
    domain too, and there javascript calls work.
    Thanks

    or...
    http://turtle.ee.ncku.edu.tw/~zulu/research/seminor02/
    http://turtle.ee.ncku.edu.tw/~zulu/research/
    JRG

  • Calling JavaScript from rangeChangeListener

    Hi,
    I can not call javaScript function from my rangeChangeListener attribute on my table. Is there a way to call JS somehow?
    My situation is following:
    I have table with tableSelectMany. I am condittionaly rendering tableSelectMany checkboxes.
    Sometimes I have no checkboxes in current page (but there is checkboxes in other pages).
    The problem is that Select all and Select none functionalities (that comes automaticaly with tableSelectMany) are not disabled for that kind of pages, so I get error when trying to select when theres nothing in the page to select.
    So I need javascript on rangeChangeListener event to check if I have checkboxes and if not - disable them.
    It looks like ADF bug. Maybe somebody had the same sort of problem or have ideas on how to handle this situation?

    Hi,
    in this case you either go for a terrible JavaScript hack, or get rid of it alltogether
        <afh:head title="DepartmentsTable">
                <style type="text/css">
                    .x2l {display:none;}
                </style>
        </afh:head>Frank

  • Embedded .swf's calling javascript from air container

    1) I have an html/ajax air app version 1.5.1
    2) This air app embeds .swf files from an external source / web server & plays the embdded .swf inside air.
    3) The embedded .swf file has a button with an onClick event
    function onClick(event:MouseEvent):void {
    ExternalInterface.call("someJavascriptMethod()" );
    4) The javascript method to be called is already parsed inside the containing Air app and is waiting to be triggered.
    5) When the onClick is triggered, the following error is thrown.
    Error: Error #2067: The ExternalInterface is not available in this container. ExternalInterface requires Internet Explorer ActiveX,
    Firefox, Mozilla 1.7.5 and greater, or other browsers that support NPRuntime.
    at Error$/throwError()
    at flash.external::ExternalInterface$/call()
    at stress_fla::MainTimeline/onClick()
    6) On investigation I found on your livedoc's website that Air does not support the ExternalInterface.call method.
    http://livedocs.adobe.com/labs/air/1/aslr/flash/external/ExternalInterface.html
    Look for Note: Adobe AIR currently does not support the ExternalInterface class.
    7) Does anyone here know how I can get an embbeded .swf file to call javascript methods in the containing air application? I have had a look at the getUrl method but this is now longer supported & even the FS command but still to no avail. I may have a work around by inserting a DOM element over the top of the embedded .swf but this is not an elegant solution & want the .swf to talk directly to the air app container.
    All help & comments welcome
    Thanks
    Kyle
    Additionally I have found
    http://help.adobe.com/en_US/AIR/1.5/devappsflash/WS5b3ccc516d4fbf351e63e3d118666ade46-7ed4 .html
    Using the Html Loader so that Actionscript can call/manipulate the dom objects. At first I was whopee but then I tried the examples listed in the help. The HTMLLoader class is only available in Air. When trying to use import flash.html.HTMLLoader; Flash C4 complains that the Definition cannot be found on compile time & therefore does not export my movie correctly. Has anyone else had this problem or have a solution??
    More additions:
    The reason the htmlLoader class was not compiling was due to the source action script provided being ActionScript 2.0 - the htmlLoader class is a 3.0 library.
    However, after more investigation I have found the current structure.
    The air app has an html base/root doc. On periodic javascript events - .swf files are downloaded via
    videos = new air.Loader();
    netStream     = new air.URLRequest(path + file);
    videos.load(netStream);
    So now I have a html container in my air app that creates a new air.Loader which downloads the external .swf file in which I want an onClick event in the action Script of the downloaded .swf file to call a Javascript method of the parent air container. Simple yea?
    Or am I making life to hard for myself? Have been looking at the security snadboxes but I don't see how I can get the .swf file to talk nicely with the outer air container. Please help if able.
    Thanks
    Kyle

    Hi Kenneth,
    Your explanation makes sense.
    I have a big JavaScript file full of special mathematical functions written by a mathematician who only knows how to program in Javascript.
    I need to call the Javascript functions from within an ActionScript library, which obviously has no UI, and thus HTML and/or HTMLLoader are not an option.
    Any ideas?
    TIA,
    mlavie

  • Calling Javascript from Flex through FAB

    What's the standard way of calling JavaScript functions from
    Flex through the FA Bridge?
    i.e. is there a new way other than navigateToURL or
    ExternalInterface.call()
    Most of the examples I've seen are scripting Flex from
    JavaScript, not the other way around.
    Thanks.

    Hello,
    You need to register the JavaScript function as a callback to
    a Flex action. You can do this from javascript in a function that
    gets called when the flash movie has finished loading. Then, when
    the Flex event is triggered it will execute the JavaScript
    function.
    Hope this helps,
    Cristian

  • Calling javascript from procedure

    Hi folks
    I am trying to call in a javascript from an onSubmit procedure after computations and validations. This process is conditional and fires on a button click.
    Heres the procedure body :
    begin
    htp.p('<script language =javascript'>)functiondoSomeThing(1,2);</script>');
    end;
    This is not working. I tried removing the branch from the on click of that button as well but, then it says error no page to branch to. Any possible way in which I can see the effects of the above procedure ?
    I want this javascript to be in procedure only, since this is supposed to act after computations and validations.
    Thanks
    Shantanu

    Hi Shantanu,
    Javascript is client-side code; computations, validations, processes and branches are server-side. In order for the javascript to run, therefore, it has to be on the rendered page - you can not call it after computations and validations without reloading the page with the javascript in it somewhere.
    If the script should only be on the page after the user clicks a specific button, you should set the button to set a value for a hidden item and use this to conditionally display the javascript. I tend to put scripts into a region on their own and use Conditional Display appropriately.
    What should the script do "after computations and validations" that can not be done by a page process?
    Andy

  • Calling applications from javafx

    hi,
    how to call other application such as winamp, firefox, etc from javafx.

    Have a look at the documentation of java.lang.ProcessBuilder [http://java.sun.com/javase/6/docs/api/java/lang/ProcessBuilder.html]
    General pointer for processes in Java:
    - you DO need to consume the content of the standard output and error output (if any) in order for your app to execute correctly.
    - "consuming" means empting their content (getting rid of it, saving it to a log, exporting it to the GUI, whatever). Can be done in separate Thread or task (see FX pointers below).
    - standard ouput stream is returned by getInputStream() in the Process class (I know the name is misleading but from Java's point of view, the process' output is an input stream).
    - error ouput stream is returned by getErrorStream() in the Process class (same)
    Pointers for processes in JavaFX:
    - use javafx.async.JavaTaskBase and javafx.async.RunnableFuture to create an async FX task to start & launch the process and to consume its streams.

  • Calling JavaScript from a SQL report?

    I am using the HTMLDB_ITEM api's to build my report. I am trying to render a text item and append an image / hyperlink to the end of my textbox which links to a custom popup page.
    I have all this working but I need to use a JavaScript call html_GetElement to pass into the URL I am building in the link.
    e.g.
    This query works fine and my popup page fires passing the value 'ABC' into the element P323_PIN on the popup page 323.
    <br><br>
    SELECT HTMLDB_ITEM.text (01, NULL, 10, 25)
    ||
    '<ah ref="javascript:html_PopUp(''f?p=&APP_ID.:323:&APP_SESSION.::::P323_PIN:ABCD'');
    ">Link</a>' pin
    FROM DUAL;
    <br><br>
    PS the hyperlink tag has been broken so it will display in the forum.
    <p>I would link to replace this with the value (if any) that the user types into the textbox (01).
    Any suggestions as I cannot seem to concatanate the right value into my url string. I think it is due to the quotes but I cant see the wood for the trees at the moment.
    Regards
    Duncan
    Message was edited by:
    Duncs

    If the at line selections is getting fired then just use this option to call the url,
    REPORT  zkb_test4.
    DATA: v_str(60) TYPE c.
    AT LINE-SELECTION.
      DATA: v_url TYPE string.
      v_url = v_str.
      CALL METHOD cl_gui_frontend_services=>execute
        EXPORTING
          document               = v_url
        EXCEPTIONS
          cntl_error             = 1
          error_no_gui           = 2
          bad_parameter          = 3
          file_not_found         = 4
          path_not_found         = 5
          file_extension_unknown = 6
          error_execute_failed   = 7
          synchronous_failed     = 8
          not_supported_by_gui   = 9
          OTHERS                 = 10.
      IF sy-subrc <> 0.
        MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
                   WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
      ENDIF.
    START-OF-SELECTION.
      v_str = 'http://sap.com'.
      WRITE / v_str.
      HIDE v_str.
    Regards
    Kathirvel

Maybe you are looking for