Mustafa Khan
Mustafa Khan

Reputation: 417

Injecting StyleSheet Object into Iframe

Is it possible to get a page's style sheet object using the stylesheet api and then inject that into an iframe that already had that page's HTML? So that you don't have to get all the CSS files. Also assuming this is happening on the same domain.

Upvotes: 4

Views: 3480

Answers (1)

guest271314
guest271314

Reputation: 1

You can iterate document.styleSheets, create a <link> element with href set to href of the current CSSStyleSheet, append the <link> element to body of <iframe> .contentDocument

const sheets = document.styleSheets;
const iframe = document.querySelector("iframe");
console.log(iframe.contentDocument.head)
for (let {href} of sheets) {
  const link = document.createElement("link");
  link.href = href;
  link.rel = "stylesheet";
  iframe.contentDocument.body.appendChild(link)
}

plnkr http://plnkr.co/edit/xl544x0FMn0WdnjioOl7?p=preview

Upvotes: 5

Related Questions