javascriptsafarimedia-queriesmatchmedia

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

  • The issue is in the formatting, oddly enough the other browsers fix the behavior even though it is malformed. It's missing an additional closing ")" parenthesis after the 1025px. Try:

    if ( window.matchMedia('(min-width:1025px)').matches) {
       console.log('match');
    
       document.addEventListener("DOMContentLoaded", function() { initialiseMediaPlayer(); }, false);
    
       function initialiseMediaPlayer() {
    
          (stuff here...)
    
       }
    
    }