Search code examples
javascriptfontsinnerhtmlgoogle-font-apigoogle-fonts

Some Google Fonts don't work on iFrame innerHTML


it's really strange, but my iFrame innerHTML doesn't accept some fonts.

Here is an example of my code:

This font works:

Head:

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Comforter&display=swap" rel="stylesheet">

Body:

<iframe id="textBox" name="richTextFeld"></iframe>
<script type="text/javascript">
    function onLoad() {
        richTextFeld.document.designMode = 'On';
        richTextFeld.document.body.style.fontFamily = "'Comforter', cursive";
        richTextFeld.document.body.style.fontSize = "16px";
        richTextFeld.document.body.style.color = "#ff0000";
        richTextFeld.document.body.innerHTML = "Some Text";
    }
</script>

And this font doesn't work (I have marked the two differences with two **):

Head:

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
**<link href="https://fonts.googleapis.com/css2?family=Raleway:wght@200&display=swap" rel="stylesheet">**

Body:

<iframe id="textBox" name="richTextFeld"></iframe>
<script type="text/javascript">
    function onLoad() {
        richTextFeld.document.designMode = 'On';
        **richTextFeld.document.body.style.fontFamily = "'Raleway', sans-serif";**
        richTextFeld.document.body.style.fontSize = "16px";
        richTextFeld.document.body.style.color = "#ff0000";
        richTextFeld.document.body.innerHTML = "Some Text";
    }
</script>

I really don't understand why the font below doesn't work, do you have an idea?

Edit: In the inspector Raleway is displayed as font, but the displayed font on the site is different (see image below). Image


Solution

  • Here is how you can change the font:

    <iframe id="textBox" name="iFrameName"></iframe>
    

    Import a font:

    iFrameName.document.body.innerHTML = "<style>@import url('https://fonts.googleapis.com/css2?family=Raleway&display=swap');*{font-family:'Raleway',sans-serif;}</style>Some Text";
    

    Use a installed font:

    iFrameName.document.body.fontFamily = "Arial";