CarlosJavier
CarlosJavier

Reputation: 1045

Setting Background Image with BrowserAction

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

Upvotes: 0

Views: 494

Answers (3)

Uzair Farooq
Uzair Farooq

Reputation: 2427

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();
}

Upvotes: 2

kevbot
kevbot

Reputation: 453

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)'"});
}

Upvotes: 1

Elliot Bonneville
Elliot Bonneville

Reputation: 53301

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]

Upvotes: 0

Related Questions