CSS Within Widgets

Posted on January 26, 2014 in Web Development

So it all started when I was looking for a weather widget for a client’s website. After looking at what felt like 300 old, dated, gross weather widgets, I finally found one that is pretty nice. Scratch that, this one is beautiful. If you haven’t checked out the Forecast.io embedable widget (and the rest of the site), you have to check it out. Long story short, the widget I added to their site looked like the one below.

Forecast.io widget
Forecast.io widget

I was able – based on their iframe URL string – to set the city name, latitude, longitude, and color for the temperature bars. While that’s a fairly decent set of options, it didn’t really provide all the styling I needed. The content was too wide and I would have liked to have been able to tweak the rest of the text colors and sizes to match the brand of my client’s. I thought “What if they could let someone (me) provide their (my) own CSS file in the URL?

Enter the CSS Variable Concept

I set out to see what it would take to allow for URL strings of an external CSS file to be passed into an iframe. The results were surprisingly simple. After all default CSS files for the widget have been included, simply add a short string that allows an external URL to be added to the page. Here is the PHP snippet that I came up with.

<?php if($_GET['css']){ ?>
    <link rel="stylesheet" href="<?php echo $_GET['css']; ?>">
<?php } ?>

In the text above, I am checking to see if the “css” GET variable has been declared and adding it as a stylesheet it it has. That’s all there is to it! After plenty of testing, it looks like this works cross-domain and overwrites classes and styles nicely.

Now, when someone wants to link up this page in an iframe, they simply need to append the CSS variable and path to the file. Example:

<iframe src="https://www.mburnette.com/iframepage?css=http://www.yourdomain.com/iframepage.css"></iframe>

Security Implications

While it’s possible that this opens up some security holes on your page, it is my understanding that simply verifying that it is a CSS file before adding it will take care of the security issue. Since a CSS file can’t run any scripts, I just quickly check to see if the file ends in CSS and add the file to the HEAD if it does. To accomplish this quickly, I also snagged a snippet from this stackoverflow thread.

function endsWith($haystack, $needle) {
    return substr($haystack, -strlen($needle)) === $needle;

<?php if(endsWith($_GET['css'],'.css')){ ?>
    <link rel="stylesheet" href="<?php echo $_GET['css']; ?>">
<?php } ?>

If you can think of any reason why this might still allow for unwanted actions, please leave me a message in the comments!

Leave a comment

Your email address will not be published. Required fields are marked *