将元素的innerHTML设置为随机字符串

时间:2020-02-21 16:03:10

标签: javascript html hash

我需要使用JavaScript使hash-paragraph的{​​{1}}成为随机字符串。

我已经尝试过了:

.innerHTML
function CreateHash() {
  var randomhash = crypto.randomBytes(20).toString('hex');
  randomhash.id = "randomhash";
  document.getElementById("hash-paragraph").innerHTML = document.getElementById("randomhash").value;
}

我丢失某些行还是<p id="hash-paragraph">This should be random string</p> <input type="submit" name="hash-click" onclick="CreateHash()">是错误的方法?

1 个答案:

答案 0 :(得分:2)

Web Crypto API标准中没有randomBytes方法。这是仅在加密NodeJS模块上可用的方法。在这种情况下,等效项为crypto.getRandomValues()MDN提供了有关它的更多信息。

编辑:crypto.getRandomValues()方法需要一个TypedArray作为参数来向其提供熵值。我附上CodePen example,说明如何生成并将其转换为适合您需要的十六进制格式。

相关问题