skip to Main Content

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();

2

Answers


  1. You should check for randomUUID to be available as Crypto is release since 2011 and randomUUID since 2021 (see Crypto – Browser compatibility). It is possible that you have a version without randomUUID. Check it via typeof. It returns undefined as a string and therefore fails. I dont see more things to test.

    function GenerateGuid() {
        if (self && self.crypto && typeof self.crypto.randomUUID === 'function') {
            console.log(self.crypto.randomUUID());
        }
        else {
            console.log("self.crypto not available");
        }
    }
    
    GenerateGuid();
    Login or Signup to reply.
  2. 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();
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search