I have a Google Chrome extension that contains only a single JavaScript file, which gets loaded for pages in a certain domain. The script is very simple, it just reads the innerHTML from a particular element, then changes the title of the page depending on what the element contained. Code below.
var status = document.getElementById("target-element").innerHTML.toLowerCase();
if(status.indexOf("string1") != -1){ //Using String.indexOf() to check for substring
document.title = "Title A";
}if(status.indexOf("string2") != -1){
document.title = "Title B";
}else{ //Running
document.title = "Title C";
}
This part works fine, and I wanted to modify it so that it could also change a page's icon as well. As the pages this script runs on don't ever have an icon linked in their header to begin with, all I have to do is add it and set it's relevant attributes. New version of the script with this implemented:
var status = document.getElementById("target-element").innerHTML.toLowerCase();
var iconLink = document.createElement('link');
iconLink.rel = "icon";
if(status.indexOf("string1") != -1){
document.title = "Title A";
iconLink.href = "icona.png";
}if(status.indexOf("string2") != -1){
document.title = "Title B";
iconLink.href = "iconb.png";
}else{
document.title = "Title C";
iconLink.href = "iconc.png";
}
document.head.appendChild(iconLink);
While this does successfully add the link tag, the icon comes up as not found because chrome looks for it in /icon.png. I also tried ./icon.png
, but the result was the same. What is the correct way to access a file that is part of a chrome extension?
Thank you for your time.
You can use Base64 to inject your icon.
<link href="data:image/x-icon;base64,AAABAAEAEB8AAA==" rel="icon" type="image/x-icon" />
Or you can try to use Web Accessibile ressource in your manifest. https://developer.chrome.com/extensions/manifest/web_accessible_resources
{
...
"web_accessible_resources": [
"images/*.png",
"style/double-rainbow.css",
"script/double-rainbow.js",
"script/main.js",
"templates/*"
],
...
}