Andy Harvey
Andy Harvey

Reputation: 12663

iframe or JS to embed Rails in 3rd party sites?

I want to create embedable widgets for a Rails app, that would allow users to interact with the app from external websites.

I was all set to try using iframes to achieve this. But then I found a couple of forum responses that seemed to suggested iframes are not the best way to achieve this, and instead to use JS to embed HTML elements. This surprised me - I thought iframes would be a clear winner simply because of the isolation of CSS and scripts.

So, what is the best way to embed (limited) app functionality in a third party website. This interaction will be limited to login and a single simple form. Is iframes of JS embed the best way to go? And as a side question, are there security issues to be aware of with either approach?

Upvotes: 0

Views: 1443

Answers (2)

Luke Vella
Luke Vella

Reputation: 746

If you want third party sites to react to interactions with your widgets then you should absolutely use javascript. Although it is possible to pass messages between different domains through an iframe it is not the most convenient to use. See https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

As for using javascript, you can simply ask your users to embed a javascript file that will render your widget. To bypass any CORS issues, your widget should interact with an API that supports JSONP responses.

Upvotes: 1

siegy22
siegy22

Reputation: 4413

I think using iframes suck hard. It's just not the feeling of a whole website, it's like a website inside another, mostly the styles won't match, or you have a scrollbar or the responsive layout is not applying right. So here's a little pro/con list:

iframe PRO:

  • requests are not cross site origin (most likely more secure)
  • "sandbox" javascript (no conflicts)

iframe CON:

  • style guides
  • history not changing (e.g. if you do a submit a form with GET you cannot paste the URL and send it to a friend)

js PRO:

  • Full control about the navigation (you can override link clicks with $.load etc).
  • Ability of changing the browser history (history API, see MDN)
  • smooth handling of html components
  • style's are automatically inherited

js CON:

I wrote a little rails plugin which allows you to embed your rails app as a js frame inside another (it's still really really beta): https://github.com/Elektron1c97/better_frame. The plugin handles most of the js problems like the link/form events and write to the browser history.

So.. If you need to run an app which should be really embed in a site like a store on another website I would use js embedding.

If you create a custom item to share like the soundcloud player you may want to use an iframe.

Upvotes: 2

Related Questions