Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you check if self.crypto.randomUUID() is available in Javascript?

I'm building a React app and have a need to generate unique UUIDs. I am trying to use the function randomUUID() from self.crypto. See: https://developer.mozilla.org/en-US/docs/Web/API/Crypto/randomUUID

If I don't want my code to explode if this runs in an unsupported browser, would this be sufficient?

function GenerateGuid() {
  if (self && self.crypto) {
    console.log(self.crypto.randomUUID());
  } else {
    console.log("self.crypto not available");
  }
}

GenerateGuid();
like image 967
AlbatrossCafe Avatar asked Oct 23 '25 15:10

AlbatrossCafe


1 Answers

I would use optional chaining to check whether self.crypto.randomUUID exists.

function GenerateGuid() {
    if (self?.crypto?.randomUUID) {
        console.log(self.crypto.randomUUID());
    }
    else {
        console.log("self.crypto not available");
    }
}

GenerateGuid();
like image 67
Barmar Avatar answered Oct 26 '25 03:10

Barmar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!