How to apply Google Web Font Loader within an iframe

2.5k views Asked by At

I'm working on a piece of code that loads Google Fonts dynamically.

Some of the content of that page is loaded within an iframe (on the same domain origin). I'm struggling to load and apply the Web Fonts within the iframe. I have access to both the parent document and the iframe. Here is my code:

<h1>FONT to test</h1>
<p>Another FONT to test</p>

<iframe src="iframe-content.html"></iframe>

<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/webfont/1.6.26/webfont.js"></script>

<script>
    WebFont.load({
        google: {
            families: [ 'Abel' ]
        },

        fontactive: function() {
            $('h1').css('font-family', 'Abel');
        }
    });
</script>

And here is the iframe contents code:

<h1>IFRAME FONT to test</h1>
<p>IFRAME Another FONT to test</p>

I tried using the "context" variable outlined here: https://github.com/typekit/webfontloader

But I didn't manage to make it work.

Thanks in advance!

2

There are 2 answers

0
ddd555 On BEST ANSWER

I managed to find out this myself.

WebFont.load({
    google: {
        families: [ 'Abel' ]
    },
    context: window.frames[0].frameElement.contentWindow,
}

This will load the font in the document inside the iframe.

3
tshimkus On

The iframe is essentially its own page so it cannot inherit anything from the page where the iframe tag lives.

If you add the styling code to iframe-content.html it should work. Here is an example:

<script src="https://ajax.googleapis.com/ajax/libs/webfont/1.6.26/webfont.js"></script>
<h1>IFRAME FONT to test</h1>
<p>IFRAME Another FONT to test</p>
<script>
    WebFont.load({
        google: {
            families: [ 'Abel' ]
        },

        fontactive: function() {
            $('h1').css('font-family', 'Abel');
        }
    });
</script>