0

i am learning how to write chrome extensions, i found one example where, using a browseaction it´s posible to change the backgroundcolor of the webpage, i am trying to do something really similar, changing the backgroundimage, but for some reason...it is not working, the js function is:

function click(e) {
  chrome.tabs.executeScript(null,
      {code:"document.body.style.background=url('ffrontier.jpg')"});
  window.close();
}

I am pretty sure it is something about my sintax but i cant figure it out, can anybody help me? THANKS A LOT

CarlosJavier
  • 1,005
  • 1
  • 16
  • 29

3 Answers3

2

First of all you need to specify the resource in manifest.json file (see Web Accessible Resources) like this:

"web_accessible_resources": ["ffrontier.jpg"]

Secondly, you should specify complete image url like this:

function click(e) {
  chrome.tabs.executeScript(null,
      {code:"var imgURL = chrome.extension.getURL('ffrontier.jpg'); document.body.style.backgroundImage='url(' + imgURL + ')'"});
  window.close();
}
Uzair Farooq
  • 2,402
  • 3
  • 24
  • 37
1

UPDATE: only external urls like url(http://www.stackoverflow.com) work, NOT local files. Sorry. I simply removed the quote marks in url() and it's working for me!

function click(e) {
  chrome.tabs.executeScript(null,
      {code:"document.body.style.backgroundImage = 'url(ffrontier.jpg)'"});
}
kevbot
  • 453
  • 1
  • 4
  • 13
0

You need to change the background-image property, not the background property (which refers to the background color of the page).

function click(e) {
  chrome.tabs.executeScript(null,
      {code:"document.body.style[background-image]=\"url('ffrontier.jpg')\""});
  window.close();
}

Something to note: document.body.style.background-image will throw an error because you can't use the - symbol in variable names. You have to use object syntax instead:

document.body.style[background-image]
Elliot Bonneville
  • 51,872
  • 23
  • 96
  • 123