编译到鸿蒙next在uni-app中crypto报错TypeError: Cannot read properties of undefined (reading 'getRandomValues')

编译到鸿蒙next在uni-app中crypto报错TypeError: Cannot read properties of undefined (reading ‘getRandomValues’)

示例代码:

try {  
  console.log("typeof crypto:",typeof crypto);  
  console.log("typeof crypto.getRandomValues:",typeof crypto.getRandomValues);  
  var rnds8 = new Uint8Array(16);  
  const res = crypto.getRandomValues(rnds8);   
  console.log("res:",res);  
} catch (e) {  
  console.log("crypto error:",e);  
}

操作步骤:

  • 本地打包然后在鸿蒙真机上运行

预期结果:

15:26:45.760 typeof crypto:, object at main.js:42
15:26:45.760 typeof crypto.getRandomValues:, function at main.js:43
15:26:45.784 res:, 106,210,46,8,40,111,162,164,176,187,37,7,158,202,246,197 at main.js:46

实际结果:

2025-05-09 15:27:23: typeof crypto: object at main.js:42
2025-05-09 15:27:23: typeof crypto.getRandomValues: function at main.js:43
2025-05-09 15:27:23: crypto error: TypeError: Cannot read properties of undefined (reading ‘getRandomValues’) at main.js:46

bug描述:

鸿蒙next中使用不了crypto.getRandomValues,typeof crypto.getRandomValues打印出来是function,但是一调用就报错TypeError: Cannot read properties of undefined (reading ‘getRandomValues’)


| 项目信息            | 信息           |
|-------------------|--------------|
| 产品分类            | uniapp/App   |
| PC开发环境操作系统     | Windows      |
| PC开发环境操作系统版本号 | win10        |
| HBuilderX类型       | 正式         |
| HBuilderX版本号      | 4.64         |
| 手机系统           | HarmonyOS NEXT |
| 手机系统版本号       | HarmonyOS NEXT Developer Beta1 |
| 手机厂商           | 华为         |
| 手机机型           | Mate60       |
| 页面类型           | vue          |
| vue版本           | vue3         |
| 打包方式           | 离线         |
| 项目创建方式        | HBuilderX    |

更多关于编译到鸿蒙next在uni-app中crypto报错TypeError: Cannot read properties of undefined (reading 'getRandomValues')的实战教程也可以访问 https://www.itying.com/category-93-b0.html

3 回复

临时解决方案:把附件里的 UniAppRuntime.har 放到 harmony-configs/libs 目录下,删除 unpackages 重新运行选择清空缓存。
经过我测试 crypto 和 uuid 可以正常使用

更多关于编译到鸿蒙next在uni-app中crypto报错TypeError: Cannot read properties of undefined (reading 'getRandomValues')的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


问题解决了,感谢!

这个问题的原因是鸿蒙NEXT环境下对Web Crypto API的实现不完整。虽然typeof检测显示crypto.getRandomValues存在,但实际调用时却报错,这表明API的实现存在问题。

解决方案建议使用uni-app的兼容方案:

  1. 使用uni.getRandomValues()替代:
const rnds8 = new Uint8Array(16);
const res = uni.getRandomValues(rnds8);
  1. 或者使用polyfill方案:
if(!window.crypto) {
  window.crypto = {
    getRandomValues: function(buffer) {
      return uni.getRandomValues(buffer);
    }
  };
}
回到顶部