Skip to content

Instantly share code, notes, and snippets.

@stevenlafl
Created May 20, 2022 15:03
Show Gist options
  • Save stevenlafl/024dd4a0f08933a7e532b36c352bfcc3 to your computer and use it in GitHub Desktop.
Save stevenlafl/024dd4a0f08933a7e532b36c352bfcc3 to your computer and use it in GitHub Desktop.
Pure Javascript to remove Print styles/CSS from webpage
function unloadStyles() {
console.log('unloading');
var links = document.getElementsByTagName('link');
for (let i in links) {
var link = links[i];
if (link.media == 'print') {
link.remove();
}
}
var styles = document.getElementsByTagName('style');
for (let i in styles) {
var style = styles[i];
if (style.media == 'print') {
console.log(style);
style.remove();
}
}
var styleSheet = document.styleSheets;
for (let i in styleSheet) {
var styleObject = styleSheet[i];
try {
for (let j in styleObject.cssRules) {
var rule = styleObject.cssRules[j];
if (rule.media) {
if (rule.media[0] == 'print') {
console.log(rule);
document.styleSheets[i].deleteRule(j);
}
else if (rule.media[0].includes('screen and')) {
console.log(rule);
var medText = rule.media[0].replace('screen and', '');
rule.conditionText = medText;
rule.media[0] = medText;
rule.media.mediaText = medText;
}
}
}
} catch (e) {}
}
}
document.addEventListener('DOMContentLoaded', function () {
unloadStyles();
});
window.addEventListener('beforeprint', function () {
unloadStyles();
});
var mediaQueryList = window.matchMedia('print');
mediaQueryList.addListener(function(mql) {
if (mql.matches) {
unloadStyles();
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment