I ran into an issue with my add-on on some websites that are making use of the document.styleSheets
Web API. Because my add-on injects a <style>
element into the page using a content script, when the website uses the document.styleSheets
to loop through the stylesheets on the page, it causes a DOM Exception about accessing a cross-site stylesheet.
Uncaught DOMException: CSSStyleSheet.cssRules getter: Not allowed to access cross-origin stylesheet
It looks like this functionality is used often by websites using React.
I think it’s a great idea to stop websites from viewing stylesheets that have been added by an extension (in fact, it’s kind of worrying that Chrome doesn’t do this), but because the DOM exception is thrown, the page doesn’t render at all.
Is there some way for the content script to add a style element to the page without it being included in the document.styleSheets
result?
Or, alternatively, is there a way for my content script to override the document.styleSheets
property so that I can filter my extension’s stylesheet out of the list?
I started working on the latter, using this code:
unfilteredStyleSheets = document.styleSheets;
document.styleSheets = () => {
const result = [];
const sheets = unfilteredStyleSheets ();
for (i = 0; i < sheets.length; i++) {
if (sheets[i].ownerNode.id != MY_STYLESHEET_ID) {
result.push(sheet[i]);
}
}
return result;
};
It worked… but then I realized that document.styleSheets
is not a function, so I was basically setting unfilteredStyleSheets to the list of stylesheets at that specific moment in time and essentially breaking the functionality of the document.styleSheets
API.
To be honest, this kind of seems like a Firefox bug. Shouldn’t Firefox throw a warning instead of an exception, like it does for other cross-site issues.