The error "crypto.getRandomValues must be defined" is thrown when the `getRandomValues` function is

The error "crypto.getRandomValues must be defined" is thrown when the
getRandomValues
function is not available in the
crypto
object. This function is used to generate cryptographically secure random numbers, and is required for the
randomBytes
function to work properly.

In the code you provided, the
crypto
object is imported from the
crypto_1
module. This module is not a standard part of the browser environment, and is typically used in Node.js environments.

To fix this error in a browser extension using Plasmo, you can use the
window.crypto
object instead of
crypto_1.crypto
. This object is available in modern browsers and provides the same functionality as the
crypto
module in Node.js.

Here's an updated version of the
randomBytes
function that uses
window.crypto
:

function randomBytes(bytesLength = 32) {
  if (window.crypto && typeof window.crypto.getRandomValues === "function") {
    return window.crypto.getRandomValues(new Uint8Array(bytesLength));
  }
  throw new Error("crypto.getRandomValues must be defined");
}


This should fix the error and allow the
randomBytes
function to generate secure random numbers in your browser extension.
Was this page helpful?