Search code examples
javascriptjqueryiframegoogle-webfontswebfont-loader

How to apply Google Web Font Loader within an iframe


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!


Solution

  • 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.