window.open传参跳转,参数加解密

481 阅读1分钟

浅记一下

一、window.open跳转页面、参数传递、跳转页获取参数、页面刷新清除url传参、AES加密解密

使用vue2项目进行演示

父页

  methods: {
    // 加密函数
    encrypt(data) {
      const encrypted = CryptoJS.AES.encrypt(
        JSON.stringify(data),
        "your-secret-key"
      ).toString();
      return encodeURIComponent(encrypted);
    },
  },
      
  mounted() {
    // 获取token并增加盐值(Salt)
    const plaintext = sessionStorage.getItem("Admin-Token") + 'Ifwf2Ejdc8sfwRfs';
    // 使用open进行页面跳转(打开新页面),并在url上传递参数
    window.open(`http://192.168.55.138:8666/?token=${this.encrypt(plaintext)}`, "_blank");
  }
      

新开页

  methods: {
    // 解密函数
    decrypt(ciphertext) {
      const decrypted = CryptoJS.AES.decrypt(
        decodeURIComponent(ciphertext),
        "your-secret-key"
      );
      let token = JSON.parse(decrypted.toString(CryptoJS.enc.Utf8));
      return token.split("Ifwf2Ejdc8sfwRfs")[0];
    },
  },
      
  created() {
    const encryptedToken = new URLSearchParams(window.location.search).get(
      "token"
    );

    // 解密token并存储sessionStorage
    sessionStorage.setItem("Admin-Token", this.decrypt(encryptedToken));

    // 3. 清除URL中的参数(不刷新页面,尽修改历史条目)
    if (encryptedToken) {
      history.replaceState(
        null, // 状态对象
        document.title, // 页面标题
        window.location.pathname // 仅保留路径,移除查询参数
      );
    }
  },

与其他方法的对比

  • window.location = "new-url":会刷新页面,因为浏览器会加载新 URL。
  • history.pushState():添加新的历史记录条目(类似点击链接),但不刷新页面。
  • history.replaceState():替换当前历史记录条目(如示例),同样不刷新页面。