How to add a dynamic query string to a link?

If you want to prevent caching you could also just use the current timestamp instead of random number.

The following code snippet finds every link on the page containing “pdf” and adds either ?r={timestamp} or &r={timestamp}.

var timestamp = new Date().getTime(),
links = document.querySelectorAll("a[href*=pdf]");
for (var i = 0, l = links.length; i < l; ++i) {
    links[i].href += [/\?/.test(links[i].href) ? '&' : '?', "r=", timestamp].join("");
}

But I’m almost sure you could achieve it in a better way, for example by disabling the browser caching in the browser’s developer tools (if it’s for debugging purposes)

Leave a Comment