How Do I Change a "style" Image in a Website Using a Chrome Extension

Viewed 194

I am trying to figure out how to change images of a website using chrome extensions that aren't just ones with "src" attributes. In my case, I am trying to change the logo on https://www.foxnews.com/ and I can see when I inspect and look in "styles" that it is the "background-image" property. The problem is that when I set it to my own image (using methods that have worked elsewhere before), nothing happens. I can change the "background-size" and "background-color", but the image will not budge. Can someone please provide a solution?

Here is my code so far: manifest.json:

{
    "name": "ChromeExtension",
    "description": "E",
    "version": "1.0",
    "manifest_version": 3,
    "web_accessible_resources": [
        {
            "resources": ["*.jpg","*.JPG"],
            "matches": ["<all_urls>"]
        }
    ],
    
    "permissions": ["storage","activeTab","scripting"],

    "content_scripts":[
        {
            "matches": ["https://www.foxnews.com/"],
            "js":["fNews.js"]
        }
    ]
}

and fNews.js:

document.getElementsByClassName("logo")[0].style.backgroundColor = '#3aa757';
document.getElementsByClassName("logo")[0].setAttribute('href','https://www.cnn.com/');
document.getElementsByClassName("logo")[0].style.backgroundSize = '50%';
document.getElementsByClassName("logo")[0].style.backgroundImage = 'chrome-extension://igdebagnkjaemmchleldelgggjpbngkl/Duck.jpg';
2 Answers

You can try injecting a css file with the changes directly into the css itself, this would override the current page css.

Create a css file with your styles for the logo:

.logo{
  background-image: url('...');
  background-color: #3aa757;
  background-size: 50%;
}

Then in your js script inject it to the page:

window.onload = async () => {
    let [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
    
    // inject css
    await chrome.scripting.insertCSS({
        target: {tabId: tab.id},
        files: ['logo.css'],
    });
}

And add permissions to manifest.json:

{
"name": "....",
...
"permissions": [
    "activeTab",
    "tabs" ,
    "scripting"
  ],
...
}

backgroundImage may contain several types of content so we need to use url() here:

document.querySelector('.logo').style.backgroundImage =
  `url("${ chrome.runtime.getURL('Duck.jpg') }");`

And we've used chrome.runtime.getURL instead of hard-coding the id of the extension.

Related