Creating an embeddable widget in Rails 4
22 Dec 2016If you wish to allow some of your content to be embedded into other websites, you can create a JS script that will enable that quite easily using Rails. Sounds good? Let’s go!
First, let’s start by adding an endpoint in our routes
file:
This will allow the client website to use our JS embed code to connect
to our app via domain.com/embed/:id
In order for this to happen smoothly, we will need to allow connections from remote sites by managing our CORS (Cross Origin Resource Sharing) policy, which would block any XHR requests from non-origin domains by default, preventing attacks to our server by anonymous requests.
We will do so by creating a private allow_iframe
method in our ApplicationController
which we can reuse if needed:
This will delete the X-Frame-Options
to which Rails 4 adds a default value of SAMEORIGIN
, as the absence of this header will make the browser “allow all” origins (only where the method is called, of course) and is more consistent to different browsers and caching issues than simply replacing its value.
Then, we will call it in the corresponding controller:
And in the show
view:
Now, lets create a simple embed.js
script in our public
folder which will be
accesed by the client website to load our embedded content:
Now all we have to do is instruct the client website to insert this simple script, where the data-content
attribute is the :id
of the desired content:
Enjoy!
Optional AJAX implementation
In case you’d like to allow AJAX functionality to this widget, great gem for managing this in Rails is the RACK-CORS gem which we can add to our Gemfile
:
And configure:
Questions?
Have a question about this post, a project or anything else?
Let's have a conversation on Twitter.