What is a JSAPI Method?
A JSAPI Method definition consists of two parts:
- A method on your JSAPI class
- A registration for that method in the constructor of your JSAPI class
Creating an empty JSAPI object
Let's create a really really basic JSAPI class. We're going to use FB::JSAPIAuto as our base class, and we strongly recommend that you do the same!
There! That was easy, wasn't it? If you pass an instance of this class back to the page, it will have two members: valid and ToString. These members are defined and registered by FB::JSAPIAuto, the base class.
Adding a New Method
To add a new method to our MyPluginAPI JSAPI interface, first we need to add the method to our class. Let's add some basic math functions, shall we?
Strong dynamic typing
What do you think the result will be? If you're a C++ programmer, it may surprise you to know that this call will actually return the integer value 20, just like it would if you'd passed it two integer values. Why? JSAPIAuto "Auto"matically converts the input values into the type expected by your method. Since your method expects two
int arguments, JSAPIAuto will convert those arguments to
int from whatever type they are – if possible.
By the same logic, though, if you accept parameters of type
Note that JSAPIAuto does not automatically accept all types, but only certain "recognized" types; other types can be forced through by using the FB::variant class as a return type, but it usually isn't a good idea since the browser won't know what to do with it.
It is often a good idea to use const parameters and accept complex objects (such as std::string or FB::JSObjectPtr) by reference.
Starting in FireBreath 1.4, you can specify optional parameters using boost::optional. For example:
you can then call it any of the following ways:
However, if you were to omit the first parameter, an exception would be thrown.
As always, the registerMethod call in the constructor is exactly the same. The most common use-case for this feature is to perform a task that takes a long time on another thread and then call the callback when finished; in that case you would want to save the callback so you have it later when you need it.
For a complete list of supported types, see Supported JSAPI types