I am trying to make a simple extension that replaces all tags on a site with an image of my own however it just doesn’t seem to work. Nothing happens whenever I load the extension and I can’t find anything online to help.
I have tried running my code directly in the console of the website and it works there but when I try to use the extension it doesn’t work.
Here is my code:
console.log("help");
var img = document.getElementsByTagName("img");
if(img){
for (let i=0;i<=img.length;i++){
img[i].setAttribute("src","https://ziggysaidgrub.github.io/images/piggies.jpg/");
}
}
and here is my manifest.json:
{
"manifest_version": 3,
"name": "Ziggify",
"description": "Turn images to Zig!",
"version": "1.0",
"action": {
"default_popup": "zig.html",
"default_icon": "images/pig_32.png",
"icons":{
"16":"images/pig_16.png",
"32":"images/pig_32.png",
"48":"images/pig_48.png",
"128":"images/pig_128.png"
},
"content_scripts": [{
"all_frames":true,
"matches": ["<all_urls>"],
"js": ["js/content.js"]
}]
}
}
What’s strange is the print statement at the start of the javascript does not appear so I don’t know what is going on.
2
Answers
I am sorry guys, I just needed to move my content script portion in the manifest.json file outside of the action part and now it works as intended.
If you for some reason want to see my bad code here is the updated manifest.json:
For starters replace this…
With this more correct loop…
However, this script will attempt to replace image paths of images that are in your extension’s document, and not those inside another document in a tab!
To access the images of a document in a tab you’d need to do…
…if you had the software (mechanism) that enables operating on documents within tabs.
Therefore, doing it the Chrome extension way (their rules, their methodology)…
You need to utilize the chrome.runtime and chrome.tabs APIs (libraries) to access and operate on tabs, which you can read about here…
https://developer.chrome.com/docs/extensions/reference/api/runtime
https://developer.chrome.com/docs/extensions/reference/api/tabs
I suggest you find a basic chrome extension example and examine how it’s done. Not one that displays a “hello world” but one that actually accesses and changes a document in a tab.