Search code examples
javascripthtmlcssgoogle-chrome-extensionfont-face

set font-face/font-family using setAttribute (javascript)


I am creating and styling a div using javascript like this:

var div = document.createElement("div");
div.setAttribute('style',  'box-shadow: 10px 10px 50px #888888; \
                            background-color: #ffb734; \
                            etc...
                           ');

I have to do it this way as I am inserting the div from a chrome extension content script.

How can I change the font face, if I have downloaded a font myFont.ttf to the same directory?

Here is what I've tried:

var div = document.createElement("div");
div.setAttribute('style',  'box-shadow: 10px 10px 50px #888888; \
                            background-color: #ffb734; \
                            @font-face {\
                                font-family: '" + 'openSans' + "'; \
                                src: url('" + 'OpenSans-Semibold.ttf' + "') \
                            } \
                           ');

But this breaks the div (it stops showing up)

Thanks in advance!

p.s. Is it a better approach to instead make a css file and include it in my manifest?


Solution

  • The value of the style attribute must match the syntax of the contents of a CSS declaration block (excluding the delimiting braces).

    That means that at-rules are not allowed in that context.