-2

I've been asked to insert a CACHEBUSTER (random number) within this third party pixel below:

<img src='http://yourdomain.com?dfew&chpcm=&chpsg=&chpcr=&chpck=&rand=INSERT_CACHEBUSTER&chpth=' width='1' height='1' border='0'>

The random number is supposed to populate in the rand URL parameter, but I do not know how to go about doing this.

  • Can you change that HTML? – Alex K. Dec 02 '14 at 15:30
  • Why do this with JavaScript? Remove your dependency on the client having JavaScript enabled and just add the random number when the HTML is generated (server-side) – Bill Dec 02 '14 at 15:43

3 Answers3

1

You could replace the 'INSERT_CACHEBUSTER' with a timestamp, like this:

var img = document.querySelector('img[src*="INSERT_CACHEBUSTER"]')
img.src = img.src.replace('INSERT_CACHEBUSTER', (new Date()).getTime())

Timestamp works better than a random number because it increments every millisecond, so there's virtually no way for it to repeat which would the case with a random number, but if you really want random:

img.src = img.src.replace('INSERT_CACHEBUSTER', Math.random())

EDIT: both solutions make it possible to hit the tracking server twice: once with the placeholder string then once again after the src is modfied. You can avoid it by either using another attribute, for example data-src:

// HTML
<img data-src='http://blahblah&rand=INSERT_CACHEBUSTER' width='1' height='1' border='0'>

// JS
var img = document.querySelector('img[data-src*="INSERT_CACHEBUSTER"]')
img.src = img.getAttribute('data-src').replace('INSERT_CACHEBUSTER', (new Date()).getTime());

or generating the tracking image in pure JS

var img = new Image();
img.width = 1;
img.height = 1;
img.src = 'http://h.nexac.com/e/a-858/s-1486/c-705/g-2423.xgi?pkey=xbue89gtzpg16&chpcm=&chpsg=&chpcr=&chpck=&rand=' + (new Date()).getTime() +'&chpth=';
document.body.appendChild(img);
pawel
  • 35,827
  • 7
  • 56
  • 53
0

var image = document.querySelector('#pixel-img');
image.src = 'http://h.nexac.com/e/a-858/s-1486/c-705/g-2423.xgi?pkey=xbue89gtzpg16&chpcm=&chpsg=&chpcr=&chpck=&rand=' + Math.round(Math.random(99999) * 100000) + '&chpth=';
<img id="pixel-img" src='http://h.nexac.com/e/a-858/s-1486/c-705/g-2423.xgi?pkey=xbue89gtzpg16&chpcm=&chpsg=&chpcr=&chpck=&rand=INSERT_CACHEBUSTER&chpth=' width='1' height='1' border='0'>
casraf
  • 21,085
  • 9
  • 56
  • 91
  • Fun fact: once you add an ID you can reference the image using `document.images['pixel-img']` – pawel Dec 02 '14 at 16:01
0

You can use also regular expression to substitute the value.

var src = $("img").prop( "src" );
src = src.replace( /(.+)(rand=)(.+)(&)(.+)/, "$1rand="+rndVal+"&$5");
$("img").prop( "src", src );

When you use regular expression, every word between ( ) can accessed using $i where i is the i-th position.

http://codepen.io/anon/pen/MYarjN

Marino
  • 56
  • 6