coder123
coder123

Reputation: 41

Appending CSS using appendChild to document doesn't work as expected

I am trying to manually add CSS for font-face to a new window using this code:

const css = '@font-face {font-family:Roboto; src:url("assets/fonts/Roboto-Black.ttf");}';
const head = this.externalWindow.document.getElementsByTagName('head')[0];
const style = this.externalWindow.document.createElement('style');
style.type = 'text/css';
style.appendChild(this.externalWindow.document.createTextNode(css));
head.appendChild(style);

When I do this it does not seem to recognise the CSS as CSS and even in the source code it isn't highlighted as CSS.

broken css image

But when I do this and write the style using document.write it work fine and loads the font as a font.

this.externalWindow.document.write('<html><head><style>' + '@font-face {font-family:Roboto ;src:url("assets/fonts/Roboto-Black.ttf");}' + '.inner{font-family: Roboto;font-size: 40pt;text-align: justify;}' + '</style></head><body onload="window.print();window.close()"><p class="head">' + this.headContents + '</p> <p class="inner">' + this.innerContents + '</p> <p class="sign">' + this.signContents + '</p></body></html>');

working css image

Upvotes: 4

Views: 1087

Answers (2)

Rounin
Rounin

Reputation: 29463

You can:

  1. Add an empty <style> element to the externalWindow.document
  2. Then grab the stylesheet object from that <style> element
  3. Then populate the stylesheet object with style rules, using insertRule

Example:

// Append <style> element to <head> of externalWindow.document
const head = this.externalWindow.document.head;
const style = this.externalWindow.document.createElement('style');
head.appendChild(style);


// Grab external stylesheet object
const externalStylesheet = style.sheet;


// Insert style rules into external stylesheet
externalStylesheet.insertRule('@font-face {font-family: Roboto; src: url("assets/fonts/Roboto-Black.ttf");}', 0);
externalStylesheet.insertRule('.inner {font-family: Roboto; font-size: 40pt; text-align: justify;}', 1);

Upvotes: 1

Matthias
Matthias

Reputation: 707

.createTextNode assumes that your input is text, not code, and escapes it as such (MDN).

Instead, try using style.innerHTML = css.

Upvotes: 0

Related Questions