motion icon indicating copy to clipboard operation
motion copied to clipboard

[FEATURE] Replace deprecated window.matchMedia.addListener with proper method

Open doctorstones opened this issue 1 year ago • 2 comments

Is your feature request related to a problem? Please describe. Standing on this page, window.matchMedia.addListener is a deprecated method and could be removed at any time

Describe the solution you'd like This method should be replaced in favour of EventTarget.addEventListener()

In packages/framer-motion/src/utils/reduced-motion/index.ts

- motionMediaQuery.addListener(setReducedMotionPreferences)
+ motionMediaQuery.addEventListener("change",setReducedMotionPreferences)

Describe alternatives you've considered The method could be wrapped in a try/catch construct, to avoid run-time errors on browser where it's not supported

doctorstones avatar Oct 04 '24 10:10 doctorstones

Are there any updates on this?

tenthyoung avatar May 27 '25 19:05 tenthyoung

Need to check if addEventListener exists. ios13 MediaQueryList.prototype.addEventListener is not defined

froyo-naux avatar Jul 22 '25 06:07 froyo-naux

FYI, The polyfill I'm using:

// https://developer.mozilla.org/en-US/docs/Web/API/MediaQueryListEvent/MediaQueryListEvent
if (
  typeof window !== 'undefined' &&
  typeof window.matchMedia === 'function' &&
  typeof MediaQueryList === 'undefined'
) {
  const testMql = window.matchMedia('')
  const proto = Object.getPrototypeOf(testMql) as MediaQueryList
  if (testMql && !('addEventListener' in proto)) {
    const addEventListenerCompat: Handler = function (type, listener) {
      if (type === 'change' && typeof listener === 'function') {
        this.addListener(listener)
      }
    }
    const removeEventListenerCompat: Handler = function (type, listener) {
      if (type === 'change' && typeof listener === 'function') {
        this.removeListener(listener)
      }
    }
    // @ts-expect-error skip
    proto.addEventListener = addEventListenerCompat
    // @ts-expect-error skip
    proto.removeEventListener = removeEventListenerCompat
  }
}

type Handler = (
  this: MediaQueryList,
  type: string,
  listener: (e: MediaQueryListEvent) => void
) => void

ambar avatar Jan 06 '26 06:01 ambar