[SalesForce] Referencing an image from a javascript file, both inside a static resource

Inside a Visualforce page, I have a static resource (MyResource.zip) which contains the following:

  • scripts/Script.js
  • img/iconoTP.gif

I'm using the Chrome notifications API to show desktop notifications of events in this page.

The following code is inside script.js:

function notify(thetitle, thebody) {
  if (!Notification) {
    return;
  }

  if (Notification.permission !== "granted")
    Notification.requestPermission();
  else {
    var notification = new Notification(thetitle, {
      icon: URLFOR($Resource.MyResource,'img/iconoTP.gif'),
      body: thebody,
    });
  }
}

And after calling the notify function, the line referencing the static resource throws an error because URLFOR isn't defined.

Is this possible in any way or should I upload my image in a different way? (i.e. not inside an static resource but as a document).

Note: this js file is correctly referenced in the VF page.

Best Answer

Found this on the Salesforce Developer forums. Maybe it will help you.

Do you want a quick (and a little bit ugly) solution ? define a global js variable with the path from the visualforce page :

<script> var globalStaticResourcePath = '{!URLFOR($Resource.thenameofyourzipfile)}'; </script>

and inside the js, every time that you are going to put the img url , add the global url var, example:

(inside script.js that is in the zip file) var imgpath = globalStaticResourcePath+'image.jpg';