How to access a Chrome Extension's icon from a content script

Viewed 1488

Inside of my Chrome extension's content script, I'm trying to modify the favicon of the site to (temporarily) set it to my extension's icon. I can't figure out the correct way to reference the extension's icons from within the content script, however. I've tried:

    favicon.href ='/images/icon-38.png';
    console.log("set href of favicon to " +favicon.href);

But the value of favicon.href ends up relative to whatever site I'm on, for example: set href of favicon to https://twitter.com/images/icon-38.png

From my manifest.json:

"icons": {
  "16": "images/icon-16.png",
  "38": "images/icon-38.png"
},

Within my background script, I can of course refer to my icons with their relative path... but how do I do it from the content script?

2 Answers

You need to specify the icons as web_accessible_resources:

"icons": {
  "16": "images/icon-16.png",
  "38": "images/icon-38.png"
},
"web_accessible_resources": [
  "images/icon-16.png",
  "images/icon-38.png"
],

And then use chrome.runtime.getURL (chrome.extension.getURL is deprecated since Chrome 58)

chrome.runtime.getURL('images/icon-16.png');
chrome.runtime.getURL('images/icon-38.png');

This should work for you

chrome.extension.getURL('images/icon-38.png')

Related