Exposing server-side API to JavaScript

The new JavaScript integration functionality will allow you to easily publish methods that can be called with JavaScript on the client side. In effect, you can publish a JavaScript API for your application. Although you will probably not find yourself using this very often, it can be useful when integrating with JavaScript frameworks or embedding within legacy sites.

Exposing a notify() method that takes a message and displays that as a notification can be done in one simple block in e.g UI.init():

Java

  1. JavaScript.getCurrent().addFunction("notify", new JavaScriptFunction() {
  2. public void call(JSONArray arguments) throws JSONException {
  3. Notification.show(arguments.getString(0));
  4. }
  5. });

This will expose the notify()-method globally in the window object. Technically it’s thus window.notify(), but you can call it by simply by notify(). Try entering notify("Hey!") into the Firebug or Developler Tools console, or javascript:notify("Hey!") into the address bar.

You’ll notice that this assumes there is a String in the first position of the array. Also, this will clutter the global namespace, which is generally not a good idea, unless you really have a specific need for that.

Let’s make a complete example with two arguments, some simple error handling, and namespacing:

Java

  1. JavaScript.getCurrent().addFunction("com.example.api.notify",
  2. new JavaScriptFunction() {
  3. public void call(JSONArray arguments) throws JSONException {
  4. try {
  5. String caption = arguments.getString(0);
  6. if (arguments.length() == 1) {
  7. // only caption
  8. Notification.show(caption);
  9. } else {
  10. // type should be in [1]
  11. Notification.show(caption,
  12. Type.values()[arguments.getInt(1)]);
  13. }
  14. } catch (JSONException e) {
  15. // We'll log in the console, you might not want to
  16. JavaScript.getCurrent().execute(
  17. "console.error('" + e.getMessage() + "')");
  18. }
  19. }
  20. });
  21. }

Using the dotted notation for the method will automatically create those objects in the browser; you’ll call this method like so: com.example.api.notify("Hey!"). You do not have to use a long name like this, though - it’s up to you and your use-case.

The second thing to notice is that we now wrapped the code in a try-catch, so that the wrong number or wrong types of arguments does not cause an ugly stacktrace in our server logs. Again, how you should react to erroneous use of your exposed API depends on your use-case. We’ll log an error message to the browser console as an example.

We’re now accepting a second (integer) argument, and using that as type for the Notification.

Finally, we’ll add a link that will call the function, and work as a Bookmarklet. You can drag the link to your bookmarks bar, and when you invoke it when viewing the application with our exposed notify()-method, you will be prompted for a message that will then be sent to the method. Here is the plain HTML code for creating such a link:

HTML

  1. <a href="javascript:(function(){com.example.api.notify(prompt('Message'),2);})();">Send message</a>

Here is the full source for our application:

Java

  1. import org.json.JSONArray;
  2. import org.json.JSONException;
  3. import com.vaadin.server.ExternalResource;
  4. import com.vaadin.server.VaadinRequest;
  5. import com.vaadin.ui.JavaScript;
  6. import com.vaadin.ui.JavaScriptFunction;
  7. import com.vaadin.ui.Link;
  8. import com.vaadin.ui.Notification;
  9. import com.vaadin.ui.Notification.Type;
  10. import com.vaadin.ui.UI;
  11. public class JSAPIUI extends UI {
  12. @Override
  13. public void init(VaadinRequest request) {
  14. JavaScript.getCurrent().addFunction("com.example.api.notify",
  15. new JavaScriptFunction() {
  16. public void call(JSONArray arguments) throws JSONException {
  17. try {
  18. String caption = arguments.getString(0);
  19. if (arguments.length() == 1) {
  20. // only caption
  21. Notification.show(caption);
  22. } else {
  23. // type should be in [1]
  24. Notification.show(caption,
  25. Type.values()[arguments.getInt(1)]);
  26. }
  27. } catch (JSONException e) {
  28. // We'll log in the console, you might not want to
  29. JavaScript.getCurrent().execute(
  30. "console.error('" + e.getMessage() + "')");
  31. }
  32. }
  33. });
  34. setContent(new Link(
  35. "Send message",
  36. new ExternalResource(
  37. "javascript:(function(){com.example.api.notify(prompt('Message'),2);})();")));
  38. }
  39. }