Is there a pure JavaScript approach to retrieving all breakpoints or media-quires of any site?

Viewed 88

I am new to JS and would like to programmatically find all the screen width based breakpoints (at least all the media-quires including min or max) applied to the current webpage. Do I need to parse the style sheets as pure text and look for breakpoints that way? Or are there alternative approaches?

I have looked at manual approaches and semi-automated tools that may help find these but I want to programmatically execute pure JavaScript code to find all the screen width based breakpoints(at least media queries) of the current webpage loaded.

@media (min-width: 1281px) {
  //CSS
}
@media (min-width: 1025px) and (max-width: 1280px) {
   //CSS
}
@media (min-width: 768px) and (max-width: 1024px) {
  //CSS
}
@media (min-width: 768px) and (max-width: 1024px) and (orientation: landscape) {
  //CSS
}
@media (min-width: 481px) and (max-width: 767px) {
  //CSS 
}
@media (min-width: 320px) and (max-width: 480px) {
  //CSS
}
//e.g. credited https://gist.github.com/gokulkrishh/242e68d1ee94ad05f488

I would expect as output all the screen width breakpoints ['320','480','481','767','768','1024','1025','1280','1281']. Thanks for any advise.

1 Answers

Access the stylesheets through the API provided. Loop over them and get the rules from each. Loop over those and filter out the ones which aren't media rules. Then you can read the conditionText from each one.

You'll need to parse the condition text to find the breakpoints.

Array.from(document.styleSheets).forEach(sheet => {
  Array.from(sheet.cssRules).forEach(rule => {
    if (rule.type === CSSRule.MEDIA_RULE) {
      console.log(rule.conditionText);
    }
  });
});
@media (min-width: 1281px) {
  body {
    background: blue;
  }
}

@media (min-width: 1025px) and (max-width: 1280px) {
  body {
    background: red;
  }
}

@media (min-width: 768px) and (max-width: 1024px) {
  body {
    background: green;
  }
}

Related