How to inject CSS with user origin in a browser extension?

288 views Asked by At

I have a very simple extension:

{
  "manifest_version": 2,
  "name": "User Style Sheet Workaround",
  "version": "1",

  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "css": ["default.css"]
    }
  ]
}

I want default.css to be injected as user origin, not as author origin. How can I do it?

1

There are 1 answers

7
wOxxOm On BEST ANSWER

Use chrome.tabs.insertCSS with cssOrigin: 'user' in the background script's URL change event.

For example, chrome.webNavigation.onCommitted (requires webNavigation permission) or chrome.tabs.onUpdated (doesn't require any special permissions).

The target sites to allow CSS injection should be added to permissions.

manifest.json:

{
  "manifest_version": 2,
  "name": "User Style Sheet Workaround",
  "version": "1",

  "background": {
    "scripts": ["bg.js"]
  },
  "permissions": ["<all_urls>"]
}

bg.js:

chrome.tabs.onUpdated.addListener((tabId, info) => {
  if (info.status === 'loading') {
    chrome.tabs.insertCSS(tabId, {
      file: 'style.css',
      cssOrigin: 'user',
      runAt: 'document_start',
      // allFrames: true,
      // matchAboutBlank: true,
    }, () => chrome.runtime.lastError); // ignoring errors
  }
});