What is wrong with crypto.getRandomValues in Inter

2019-04-08 04:02发布

问题:

The following code generates 3 random numbers by using window.crypto.getRandomValues. According to the developer's documentation (Microsoft MSDN and Mozilla MDN), this should work both in IE and in Chrome.

But in reality it works only in Chrome, not Internet Explorer 11. According to Microsoft, this code should work - they have given a similar code sample as the one listed below (see MSDN link above).

What is wrong? And how can it be fixed so it will work in both browsers?

var randomValuesArray = new Int32Array(3);
var crypto = window.crypto;
crypto.getRandomValues(randomValuesArray);

var outputString = "";
for (var i = 0; i < randomValuesArray.length; i++) {
  if (i > 0) outputString += ",";
  outputString += randomValuesArray[i];
}
console.log(outputString);

Try this snippet in Chrome first, there it shows correctly something like

-513632982,-694446670,-254182938

in an alert popup.

Then, copy this question's URL and try it in Internet Explorer 11 - there it is showing:

Error: { "message": "Unable to get property 'getRandomValues' of undefined or null >reference", "filename": "https://stacksnippets.net/js", "lineno": 15, "colno": 2 }


Some background: I wanted to try out this code to generate Guids in Javascript, then I found this issue.


(Update: According to James Thorpe's excellent answer below, I fixed the Guids in JavaScript source code.)

回答1:

According to the MDN, this feature is considered experimental in IE11. As such, it is prefixed with ms, and is accessible via window.msCrypto:

var randomValuesArray = new Int32Array(3);
var crypto = window.crypto || window.msCrypto;
crypto.getRandomValues(randomValuesArray);

var outputString = "";
for (var i = 0; i < randomValuesArray.length; i++) {
  if (i > 0) outputString += ",";
  outputString += randomValuesArray[i];
}
console.log(outputString);