0

I got an application that serves widgets inside iframes of other websites. So far so good but how can I allow these widgets views only to be loaded inside an iframe and not directly?

This should work

<iframe src="http://www.example.com/widgets/example">

But typing in http://www.example.com/widgets/example directly into a browser shouldn't be allowed.

What is or is there a best way to achieve this in rails?

Cojones
  • 2,930
  • 4
  • 29
  • 41
  • are these widgets stored inside a model? – DMH Apr 27 '16 at 13:10
  • I have several models that serve widgets but it's all under widgets_controller if that's helping? – Cojones Apr 27 '16 at 15:48
  • though this isnt 100% fool proof you could pass a param on your iframes and have a `before_filter` on the `WidgetsController` that checks for the params presence. If it isnt there it redirects to a page of your choice. Happy to write this more as an answer if you wish. – DMH Apr 28 '16 at 09:35
  • Thought about this as well but what about people who actually purposely try to load the widgets without an iframe? All they gotta do is look in the code and copy the parameter to make it work, no? – Cojones Apr 28 '16 at 10:50

1 Answers1

0

You need first to check if your page window is the same as parent window if not then your page inside an iframe:

function inIframe () {
  try {
    return window.self !== window.top;
  } catch (e) {
    return true;
  }
}

Then if not you can remove everything in DOM:

// Pure JS something like
var myNode = document.getElementById("foo");
myNode.innerHTML = '';
// jQuery
$('html').empty();

OR you can redirect to an empty page that say its not allowed to be viewed outside of iframe:

 window.location = "http://www.yourul.com/empty_page";

Referring to

Community
  • 1
  • 1
mohamed-ibrahim
  • 10,837
  • 4
  • 39
  • 51