Skip to content

Instantly share code, notes, and snippets.

@anonyco
Created August 7, 2019 23:52
Show Gist options
  • Save anonyco/91a160a7f617c5b4e2e5cc679964344e to your computer and use it in GitHub Desktop.
Save anonyco/91a160a7f617c5b4e2e5cc679964344e to your computer and use it in GitHub Desktop.
Quick & dirty way to inline all of the CSS on a page into style attributes from the console.
(function(){
const setProps = new WeakMap;
for (const ele of document.getElementsByTagName("*"))
setProps.set(ele, new Set);
function parseRules(ruleSet) {
for (const rule of ruleSet)
if (rule.type === 1) { // STYLE_RULE
for (const ele of document.querySelectorAll(rule.selectorText)) {
const setObj = setProps.get(ele);
for (const prop of rule.style)
setObj.add(prop);
}
} else if (rule.type === 3 || rule.type === 4) { // import or media
if (!rule.media.mediaText || matchMedia(rule.media.mediaText).matches) {
if (rule.type === 4) parseRules(rule.cssRules); // MEDIA_RULE
else try{ parseRules(rule.styleSheet.cssRules); }catch(e){} // IMPORT_RULE
}
} else if (rule.type === 6) { // PAGE_RULE
// nothing to do here
} else if (rule.type === 7) { // KEYFRAMES_RULE
// nothing to do here
} else if (rule.type === 12) { // SUPPORTS_RULE
if (!rule.conditionText || CSS.supports(rule.conditionText)) {
parseRules(rule.cssRules)
}
}
}
for (const sheet of document.styleSheets)
if (!sheet.disabled && sheet.cssRules)
try { parseRules(sheet.cssRules); } catch(e){}
for (const ele of document.getElementsByTagName("*")) {
const compStyle = getComputedStyle(ele), liveStyle = ele.style;
for (const cssProp of setProps.get(ele)) {
// check if this style is really needed (to compensate for CSSReset sheets and such)
var trueValue = compStyle[cssProp];
liveStyle.setProperty(cssProp, "unset", "important");
if (compStyle[cssProp] === trueValue) {
liveStyle.removeProperty( cssProp );
} else {
liveStyle.setProperty(cssProp, "inherit", "important");
if (compStyle[cssProp] === trueValue) {
liveStyle[cssProp] = "inherit";
} else {
// this style property really is needed
liveStyle[cssProp] = trueValue;
}
}
}
}
for (const sheet of document.styleSheets)
sheet.diabled = true; // disable all stylesheets because they are no longer needed.
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment