Skip to content

Instantly share code, notes, and snippets.

@reyronald
Last active October 4, 2022 14:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reyronald/6b11c19a844ba849780507c414b8dac3 to your computer and use it in GitHub Desktop.
Save reyronald/6b11c19a844ba849780507c414b8dac3 to your computer and use it in GitHub Desktop.
import { useEffect } from "react";
function useEmulateMediaPrint() {
useEffect(() => {
const modifiedCSSRules: Map<CSSMediaRule, string> = new Map();
for (const styleSheet of document.styleSheets) {
for (const cssRule of styleSheet.cssRules) {
if (cssRule instanceof CSSMediaRule) {
const hasPrint = Array.from(cssRule.media).some(
(media) => media === "print" || media === "not print",
);
if (hasPrint) {
modifiedCSSRules.set(cssRule, cssRule.media.mediaText);
cssRule.media.mediaText = cssRule.media.mediaText.replaceAll("print", "screen");
}
}
}
}
return () => {
for (const [cssRule, mediaText] of modifiedCSSRules) {
cssRule.media.mediaText = mediaText;
}
};
}, []);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment