简体   繁体   English

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

[英]Set element's innerHTML to random string

I need to make hash-paragraph 's .innerHTML to random string with JavaScript.我需要使用 JavaScript 将hash-paragraph.innerHTML变成随机字符串。

I've tried this:我试过这个:

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

Am i missing some rows or var randomhash = crypto.randomBytes(20).toString('hex');我是否缺少一些行或var randomhash = crypto.randomBytes(20).toString('hex'); is a wrong way to go?走错路了吗?

There's not a randomBytes method in the Web Crypto API standard. Web Crypto API 标准中没有randomBytes方法。 This is a method only available on the Crypto NodeJS Module.这是一种仅在 Crypto NodeJS 模块上可用的方法。 The equivalent in this case would be crypto.getRandomValues() .在这种情况下,等效项是crypto.getRandomValues() The MDN provides more information about it. MDN提供了有关它的更多信息。

Edit: The crypto.getRandomValues() method, requires a TypedArray as parameter to feed it with the entropy values.编辑: crypto.getRandomValues()方法需要一个 TypedArray 作为参数来为其提供熵值。 I attach a CodePen example showing how generate it and convert the result to a hex format suitable for your needs.我附上了一个CodePen 示例,展示了如何生成它并将结果转换为适合您需要的十六进制格式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM