Recently, a few customers ran into a problem in an Angular web application where an exception was thrown. Because of this problem, you couldn’t use a major part of the application. As a developer, I want to have clear instructions on how to reproduce an issue to not waste time. Good customer support or customers willing to share more details beyond “It isn’t working for me” can provide meaningful information to make the life of developers easier. Customer support wasn’t able to reproduce the issue on their devices, yet it was consistently happening for a few customers.

When this issue was brought up, I did what I typically do when encountering issues like this. This article is about this particular problem as well as debugging critical issues.

Finding the Root Cause

  • I used Instana, which is a great SaaS for monitoring microservices and websites. Through our monitoring tool, I was able to confirm that the error occurred for a few customers as well as the user actions that led to the issue. Even with this information, I couldn’t reproduce the issue at first.
  • I had the error stack trace thanks to our monitoring tool. With this, I found the code that caused the exception to be thrown. As you can see below, this code is querying all stylesheets in the DOM and doing something with the CSS rules of each stylesheet.
const styleSheets = Array.from(document.styleSheets);
	for (let style of styleSheets) {
	   if (style instanceof CSSStyleSheet && style.cssRules) { // crash
	      ... // do something with the CSS rules of each style sheet
	   }
	}
Uncaught DOMException: Failed to read the 'cssRules' property from 'CSSStyleSheet': Cannot access rules
  • Our monitoring tool also provides browser data, so I checked which browsers were affected the most. It turned out it’s mainly recent versions of Chromium-based browsers like Google Chrome. As many of my coworkers use Google Chrome as the main browser for development, I found it strange that no other developer stumbled upon this yet.
  • There were no tests for this function. I tried to replicate the issue with unit tests with Jest, but the tests ran through successfully.
  • I searched online for this particular error message and found some helpful posts regarding rather recent changes in Chrome. In the latest version of Chrome, CORS security rules are also applicable for stylesheets (similar to Iframe rules). You can load and render them, but you cannot access the content stylesheets loaded from another domain through JavaScript. While this information was helpful, I still did not understand why this should be a problem.

#angular #javascript #css #programming #software-development

How to Fix the “Failed to Read the CSSRules Property From CSSStyleSheet” Error
41.55 GEEK