开发者

cssRules/rules are null in Chrome

My chrome extension needs to modify certain css rules on user's page. Accessing styles via document.styleSheets only gives access to styles linked from within the same domain. Other elements of document.styleSheets array have cssRules/rules set to null.

Why is it cross domain policy applies here? Styles are being applied anyway regardless of their origin, so what is the point? And how to get around it in my case?

EDIT:

The reason I need to MODIFY user css rules (as opposed to simply adding my own) is that I need to protect custom element injected by extension from being affected by * rules. se开发者_开发百科e details in this question


Content scripts don't have any cross-domain privileges comparing to a regular javascript, so any limitations are carried over. See related question #1, question #2.

You can inject your own css style in the manifest:

"content_scripts": [
    {
      "matches": ["http://www.google.com/*"],
      "css": ["mystyles.css"]
    }
]

where you can try to overwrite original styles by defining rules with higher specificity.

You can also just tweak concrete element styles through javascript:

document.getElementById("id").style.property="value";


I fixed my version of the issue by changing the url from http:// to https://. Doh!


First, content scripts can't access cross-origin scripts. Second, you can fetch cross-origin scripts from the background service worker (MV3) in a Chrome Extension.

What I am doing in my Chrome Extension's content script is using this to iterate over the stylesheets and sending the failed stylesheet link to the background script in the catch statement

let styleSheets = [];
// Iterating over all stylesheets
[...document.styleSheets].map(function(styleSheet) {
  try {
    [...styleSheet.cssRules].map(function(cssRule) {
      styleSheets.push(cssRule);
    });
  } catch (e) {
    styleSheets.push(null);
    // Send failed stylesheets to service worker from here
  }
});

And in the background server worker, using this function to get the stylesheet.

fetch(styleSheetUrl)
  .then((response) => {
    if (response.status >= 200 && response.status < 300) return response.text();
    else return false;
  })
  .then((styleSheet) => {
    console.log(styleSheet);
  });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜