• 小程序使用jsencrypt加密,报Uncaught TypeError: Cannot read property ‘appName‘ of undefined问题


    转自:https://www.jianshu.com/p/2b8f0869aa37
    小程序使用jsencrypt对参数进行aes加密,在手机网页端可以正常使用,在小程序项目安装后使用报错。由于jsncrypt代码里面含有window、document、navigator对象,这些对象可以在pc端、移动端的浏览器使用,但是小程序没有这些对象,所以直接在小程序引入jsencrypt.js会直接报错,下面主要介绍如何在jsencrypt.js里面对这些对象进行兼容。

    问题:Uncaught TypeError: Cannot read property 'appName' of undefined

    修改代码目录

    解决步骤:

    (1)源代码

    if (j_lm && (navigator.appName == "Microsoft Internet Explorer")) {
        BigInteger.prototype.am = am2;
        dbits = 30;
    } else if (j_lm && (navigator.appName != "Netscape")) {
        BigInteger.prototype.am = am1;
        dbits = 26;
    } else { // Mozilla/Netscape seems to prefer am3
        BigInteger.prototype.am = am3;
        dbits = 28;
    }

     navigator主要是对浏览器的判断,同时小程序中没有appName,直接删除或者保留最后一个else即可。这个解决后还会有其他的问题按照报错做兼容处理即可

    BigInteger.prototype.am = am3;
    dbits = 28;

    (2)兼容window.crypto

    if (window.crypto && window.crypto.getRandomValues) {
      // Extract entropy (2048 bits) from RNG if available
      var z = new Uint32Array(256);
      window.crypto.getRandomValues(z);
      for (t = 0; t < z.length; ++t) {
        rng_pool[rng_pptr++] = z[t] & 255;
      }
    }

    注释上面代码改为下方代码

    var getRandomValues = function (array) {
      for (var i = 0, l = array.length; i < l; i++) {
        array[i] = Math.floor(Math.random() * 256);
      }    return array;
    }
    var z = new Uint32Array(256);
    getRandomValues(z);

    (3)兼容window.removeEventListener、window.detachEvent,直接将所有的监听事件注释即可。

    if (window.removeEventListener) {
      window.removeEventListener("mousemove", onMouseMoveListener_1, false);
    }
    else if (window.detachEvent) {
      window.detachEvent("onmousemove", onMouseMoveListener_1);
    } //这个可以不用注释
    if (window.addEventListener) {
      window.addEventListener("mousemove", onMouseMoveListener_1, false);
    }
    else if (window.attachEvent) {
      window.attachEvent("onmousemove", onMouseMoveListener_1);
    }

    (4)JSEncrypt对象不存在,直接注释即可。

    window.JSEncrypt = JSEncrypt
  • 相关阅读:
    【源码学习之spark core 1.6.1 standalone模式下的作业提交】
    【源码学习之spark streaming 1.6.1 】
    spark udf 初识初用
    spark 累加历史 + 统计全部 + 行转列
    spark 都用了哪些开源东东
    kafka 官方示例代码--消费者
    104. 二叉树的最大深度
    237. 删除链表中的节点
    Leetcode-167. Two Sum II
    Leetcode-215. Kth Largest Element in an Array
  • 原文地址:https://www.cnblogs.com/cailijuan/p/16043308.html
Copyright © 2020-2023  润新知