14

Is there a way I can use Javascript to include a CSS file only if the top frame URL contains the string "facebook.com"?

Short pseudo code:

if top.frame.url.contains("facebook.com"):
   include("style-facebook.css");

2 Answers 2

32

A quick document.write-based solution would be:

<script type="text/javascript">
    if (/facebook\.com/.test(window.top.location.host)) {
        document.write('<link rel="stylesheet" type="text/css" href="stylefacebook.css" />');
    }
</script>

Or using the dom:

<script type="text/javascript">
    if (/facebook\.com/.test(window.top.location.host)) {
        var lnk = document.createElement('link');
        lnk.type='text/css';
        lnk.href='stylefacebook.css';
        lnk.rel='stylesheet';
        document.getElementsByTagName('head')[0].appendChild(lnk);
    }
</script>

Or with jquery:

<script type="text/javascript">
    if (/facebook\.com/.test(window.top.location.host)) {
        $('head:first').append('<link rel="stylesheet" type="text/css" href="stylefacebook.css" />');
    }
</script>
Sign up to request clarification or add additional context in comments.

3 Comments

Weird thing, but it seems that inside a facebook app ("apps.facebook.com/myapp") window.top.location.host returns undefined :/
@Joel my work around was to compare window.top.location with window.location
As of 2025 the first solution (document.write) is deprecated, but the other ones (using the DOM) still work pretty well.
2
<script type="text/javascript">
//<![CDATA[
if ("condition is satisfied") {
    if (document.createStyleSheet) {
        document.createStyleSheet('http://server/style-facebook.css');
    } else {
        var styles = "@import url(' http://server/style-facebook.css ');";
        var newSS = document.createElement('link');
        newSS.rel = 'stylesheet';
        newSS.href = 'data:text/css,' + escape(styles);
        document.getElementsByTagName("head")[0].appendChild(newSS);
    }
}
//]]>
</script>

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.