Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 253
Mustafa Khan Avatar asked Sep 01 '25 10:09

Mustafa Khan


1 Answers

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

like image 72
guest271314 Avatar answered Sep 04 '25 01:09

guest271314