Now that you know how to provide services to guest code, you can practice calling guest code back from the host.
Create guest code
Assume your third-party guest code is as follows (also available here):
This code expects the host to provide an object
timerService containing a method
registerListener. The guest code passes a callback
function of its own to that method, and the host code calls that
function back periodically with a parameter,
contains a property called
Create host page with services
Now create your host page like this (also available here):
Though simple, this example demonstrates quite a few aspects of constructing a two-way interface between host and guest code:
timerService object is declared.
caja object is used to tame the timer
service. We want the top-level object to be read-only (we don't want
guest code to mess with it), and we want to allow guest code to call
callListeners function is defined; it
will be called periodically by the
event object is constructed to pass to the
guest code. Note that this too must be tamed. Specifically, imagine
that we had several pieces of guest code using this service. To
prevent one guest from damaging information seen by another, we must
event object from tampering. We do so by
making it a read-only record and ensuring that its
field is a
string, which cannot be modified.
(5) the guest code function is actually called here. It is
invoked like a regular function; Caja will implicitly
its arguments so that the guest code gets only the tamed view of the event.
(6) we invoke the guest code as before, passing the tamed API.
Loading the host page and pressing the button should give you a result like this:
Run it yourself
- You created an API such that guest code and host code could call each other; and
- You learned to reason about how your API could be used as an attack vector and the steps you can take to avoid that.