0

how can I do a Chrome extension that replaces images with other images?

Here's my manifest.json code so far:

{
  "name": "HaramB",
  "version": "69.0.420.666",
  "manifest_version": 2,
  "description": "This is HaramB's own extension!",
  "browser_action": {
    "default_icon": "images/icon.png",
    "default_popup": "popup.html",
    "default_title": "HaramB"
  },
  "permissions": [
    "activeTab",
    "https://ajax.googleapis.com/"
  ],
  "icons": {
    "128": "images/icon.png"
  },
  "web_accessible_resources": [
    "images/nicolas.jpg"
  ],
  "content_scripts": [{
    "matches": ["http://*/*", "https://*/*"],
    "js": ["onPage.js"],
    "css": ["onPage.css"]
  }]
}

And here's my onPage.js code:

var picture = "images/nicolas.jpg";
document.getElementsByTagName("img").setAttribute("src", picture);

Dont't care about the popup.html or the onPage.css files.

It's the onPage.js file i want it to do it with, if it's not possible, tell me.

mplungjan
  • 169,008
  • 28
  • 173
  • 236
drstuggels
  • 122
  • 2
  • 12

1 Answers1

2

document.getElementsByTagName() returns an Array of elements. This means you need to loop through the array and call the methods you want on them individually, like so:

var picture = "images/nicolas.jpg",
    images = document.getElementsByTagName("img");

for (var i = 0; i < images.length; i++) {
    images[i].setAttribute("src", picture);
};

Note: it is preferable to use images[i].src = ... to using setAttribute as detailed in this question

Community
  • 1
  • 1
ppajer
  • 3,045
  • 1
  • 15
  • 22
  • document.images – nick Mar 18 '17 at 20:12
  • @ppajer It kinda works, but all images are just showing as not found. Is it the **css**? – drstuggels Mar 18 '17 at 20:46
  • @JUSTSOMERANDOMGUY You need to get an absolute url to set as the src, otherwise it will try to look for it relative to the current url. If the image is stored inside your extension, [you have to get it via `chrome.extension.getUrl()`](http://stackoverflow.com/questions/10865789/embedding-images-into-a-chrome-extension) – ppajer Mar 19 '17 at 01:52