'Safari ignores window.matchMedia
I'm using window.matchMedia conditional in order to avoid the inject of a video in mobile devices. CanIUse reports that matchMedia is going to work smoothly since Safari 9 (I'm testing on it), but my code is completely ignored:
if ( window.matchMedia("(min-width: 1025px").matches) {
console.log('match');
document.addEventListener("DOMContentLoaded", function() { initialiseMediaPlayer(); }, false);
function initialiseMediaPlayer() {
(stuff here...)
}
}
This code works perfectly on Chrome, Chromium, Firefox, IE and Edge.
Does anyone had a similar issue?
Solution 1:[1]
For anyone else who may come across similar issues, I found that in safari you need to include 'screen and' as well as the width setting. Other browsers seem to assume that you are talking about the screen width but safari needs it specified, at least in my case. so would be something like:
if ( window.matchMedia('screen and (min-width:1025px)').matches) {}
in this case
Solution 2:[2]
In my case, it was that Safari uses .addListener() instead of addEventListener() on the mediaQueryList.
Solution 3:[3]
If someone stumbles across this too, in my case the problem was, that safari doesn't have the .onchange property on the MediaQueryList interface.
This was just resolved in Safari 14, but the release is rather new, so use (the deprecated) .addListener if you want to ensure backwards compatibility.
Source: https://developer.mozilla.org/en-US/docs/Web/API/MediaQueryList/onchange
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mix3d |
| Solution 2 | docta_faustus |
| Solution 3 | Mayor Mayer |
