Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mind that it doesn't work in Firefox #8

Open
oliviertassinari opened this issue Nov 2, 2020 · 1 comment
Open

Mind that it doesn't work in Firefox #8

oliviertassinari opened this issue Nov 2, 2020 · 1 comment

Comments

@oliviertassinari
Copy link

mui/material-ui#17595

@audunru
Copy link

audunru commented Mar 30, 2022

This seems to work in Firefox and Chrome:

import { useState, useEffect } from 'react';

export const usePrint = (): boolean => {
  const [isPrinting, setIsPrinting] = useState(false);

  useEffect(() => {
    const handleBeforePrint = (): void => setIsPrinting(true);
    const handleAfterPrint = (): void => setIsPrinting(false);

    window.addEventListener('beforeprint', handleBeforePrint);
    window.addEventListener('afterprint', handleAfterPrint);

    return (): void => {
      window.removeEventListener('beforeprint', handleBeforePrint);
      window.removeEventListener('afterprint', handleAfterPrint);
    };
  }, []);

  return isPrinting;
};

This works in Chrome, but not in Firefox:

export const usePrintMatchMedia = (): boolean => {
  const [isPrinting, setIsPrinting] = useState(false);

  useEffect(() => {
    const handleMediaQueryEvent = (event: MediaQueryListEvent): void => {
      setIsPrinting(event.matches);
    };

    const mediaQuery = window.matchMedia('print');
    // iOS <=13 has no support forfor addEventListener/removeEventListener on MediaQueryList,
    // but supports addListener
    if (mediaQuery.addEventListener) {
      mediaQuery.addEventListener('change', handleMediaQueryEvent);
    } else if (mediaQuery.addListener) {
      mediaQuery.addListener(handleMediaQueryEvent);
    }

    // Trigger on initial render
    setIsPrinting(mediaQuery.matches);

    return (): void => {
      if (mediaQuery.removeEventListener) {
        mediaQuery.removeEventListener('change', handleMediaQueryEvent);
      } else if (mediaQuery.removeListener) {
        mediaQuery.removeListener(handleMediaQueryEvent);
      }
    };
  }, []);

  return isPrinting;
};

Using beforeprint/afterprint, the layout visibly changes in the main browser window if you use this to adjust it. Using mediaqueries, it only changes in the print preview (but again, only in Chrome).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants