JavaScript - Check if Object URL has been used

889 Views Asked by At

I can create an object URL like this:

let pixel = "iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==";
let data = atob(pixel);
let buffer = new ArrayBuffer(data.length);
let array = new Uint8Array(buffer);
for (var i = 0;i<data.length;i++){
    array[i]=data.charCodeAt(i);
}
let blob = new Blob([buffer], {type: 'image/jpeg'});
let url = URL.createObjectURL(blob);

And I can revoke an object URL like this:

URL.revokeObjectURL(url);

But what I would like to do is automatically revoke the URL after one use.

Is there a way to check if an object URL has been accessed?

Thank you in advance.

EDIT:

In this case, I can't just trigger a function when I use the URL. Instead, I would like to be able to check if it has been used even OUTSIDE of the page. An example would be if someone typed the URL into the address bar, this can't call javascript AFAIK.

1

There are 1 best solutions below

3
On

If you don't have an API to do this, you could use localStorage to track this.

You could have 2 methods,

  • addUrlStatus - which takes a url as input and checks whether it has been accessed in the past.

  • updateUrlStatus - which sets the status of a url to true in localStorage once the user has used the url (not sure what action defines this in your code).

So you could do something like,


let pixel = "iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==";
let data = atob(pixel);
let buffer = new ArrayBuffer(data.length);
let array = new Uint8Array(buffer);
for (var i = 0;i<data.length;i++){
    array[i]=data.charCodeAt(i);
}
let blob = new Blob([buffer], {type: 'image/jpeg'});
let url = URL.createObjectURL(blob);
addUrlStatus(url);


function addUrlStatus(url) {
  var _url = localStorage.getItem(url);
  if(!_url) {
    localStorage.setItem(url, false); // false indicates it hasn't been used yet.
    return;
  }
}


// this function needs to be called when the user has used the url.
function updateUrlStatus(url) {
  localStorage.setItem(url, true);
  URL.revokeObjectURL(url);
}