Undefined
Undefined

Reputation: 764

CSS injection using chrome extension

So I have been redesigning some websites just for my own usage using chrome extension.

My goal is to inject css into a website so it would be using as a main css or it would replace some main css's codes.

What I have is the fallowing:

JS:

var style = document.createElement('link');
style.rel = 'stylesheet';
style.type = 'text/css';
style.href = chrome.extension.getURL('styles.css');
(document.head||document.documentElement).appendChild(style);

Manifest file:

{
  "name": "Extension",
  "version": "0",
  "description": "",
  "manifest_version": 2,
  "permissions": ["tabs", "https://www.youtube.com/*"],
    "content_scripts": [
    {
        "matches": [ "https://www.youtube.com/*"],
        "js": ["inject.js"],
        "all_frames": true
    }
  ],
  "web_accessible_resources": ["styles.css"]
}

And of course my css file named styles.css

The problem I am having is once I load the page, it loads in an old style and then just before it finished loading my custom css hits the road and then the styles are changed of the website. How can I make so the styles for the website would be changed as soon as it starts loading the content so the changes will not be seen whatsoever.

There is a gif image to show you what I mean by that:

enter image description here

Upvotes: 0

Views: 339

Answers (1)

Xan
Xan

Reputation: 77482

You don't need to do programmatic injection (which happens, by default, at "run_at": "document_idle", and that is exactly your problem).

Just change your manifest to this:

{
  "name": "Extension",
  "version": "0",
  "description": "",
  "manifest_version": 2,
  "permissions": ["tabs", "https://www.youtube.com/*"],
  "content_scripts": [
    {
        "matches": [ "https://www.youtube.com/*"],
        "css": ["styles.css"],
        "all_frames": true
    }
  ]
}

If you still need to do it programmatically, then you need to add "run_at": "document_start"

Upvotes: 1

Related Questions