I would like to add an extra stylesheet for my site if it's being embedded inside an iframe on another site.

I found a JS method to try detecting an iframe embed over here: https://stackoverflow.com/questions/326069

Basically, you can run a script like:

if (top === self) { not in a frame } else { in a frame }

But I was wondering if it's possible to have that code add a stylesheet to the page in Drupal. Or maybe if there were some way to do it in Drupal, in hook_init() or something, that would be even better...

A final method I could think about is using the JS above to maybe add a URL parameter like ?embed=TRUE so I can detect that and add a stylesheet... but that would require a refresh inside the iframe :-/

1 Answer 1


You could...

  • munge the window.location object to add the additional param, but that will force the page to reload. From there you can access the param in Drupal and write server-side code to do a drupal_add_css().
  • Use jQuery (which comes with Drupal) to add the CSS directly.
  • Use jQuery to add a link to the remote stylesheet.

Example of the third method:

if (top !== self) {
  var cssURL = 'http://example.com/my/stylesheet.css';
  $('head').append('<link rel="stylesheet" href="' + cssURL + '"/>');

I would think that as long as you can predict the stylesheet name, the last option is going to be the most elegant.

Note that you would want to add the JavaScript to the document with drupal_add_js() in Drupal.

  • The third method is closest to what I think I'd like to do... I'll work on it, and if it works in the iframe (I've never dynamically added CSS like that via JS), I'll give this the checkmark :) Aug 16, 2011 at 21:20
  • I've added something along those lines to an iframe-detect.js file, which I've included in my theme's .info file. One more question: Is there a simple way to let the URL detect whether or not it should be https:// instead of http://? Aug 16, 2011 at 21:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.