Need to append a random string or int to the end of file URL being called in JS

Viewed 178

I'm working with a set of files that are getting updated automatically multiple times a day and being called by two different scripts with a similar purpose. I need browsers to not cache them as they are always changing.

The current Javascript code looks like this:

profile_filename: window.location.origin + "/pdf/2021GraduateForm-4-29-2021v1.csv",

And the goal is to make the file look more like this but using a random value each time:

profile_filename: window.location.origin + "/pdf/2021GraduateForm-4-29-2021v1.csv?123456789",

Does anyone have any advice for how I can make this change, where '123456789' would be something random. Most of the documentation I've seen is for PHP and doesn't include the 'window.location' that I'm using.

2 Answers

If you serve these files and wand browsers not cache the files, must set extra header like this: responce.setHeader('Cache-Control', 'no-store, max-age=0');

If you want to create a unique query string ?.... i think that can use the time like this: profile_filename: window.location.origin + "/pdf/2021GraduateForm-4-29-2021v1.csv"+"?"+(new Date).toJSON()

If you want a "like random" value in query string, use for example something like this: profile_filename: window.location.origin + "/pdf/2021GraduateForm-4-29-2021v1.csv"+"?"+ crypto.createHash('md5').update((new Date).toJSON(), 'utf8').digest('hex');

if you just need to add unique numbers at the end of the path, and your needs don't require totally random number generating, you can add the timestamp instead.

profile_filename: window.location.origin + `/pdf/2021GraduateForm-4-29-2021v1.csv?${Date.now()}`,

Because timestamp is cumulative, it will be unique number

Related