url参数之Base64的编码与解码

url参数有敏感信息时,可通过此方式进行简单的保护
2020-09-28 02:02 2020-09-28 02:48

源码

/**
 * url参数编码设置和获取
 *
 */
export const urlParams = {
  // 获取url Base64格式参数,return {key: val}
  getQuery (queryStrParam) {
    // const queryStrMatch = window.location.href.match(/\?([^\/]*)/); // 参数格式/?xxxx
    const queryStrMatch = window.location.href.match(/\?.*urlParams=([^\/&]*)/); // 参数格式/?urlParams=xxxx
    // 若已传入queryStrParam,优先解析queryStrParam
    let queryStr = queryStrParam || (queryStrMatch && queryStrMatch[1]) || ''
    if (window.decodeURIComponent) {
      // 这里解码2次是因为浏览器会自动自动再编码一次
      queryStr = window.decodeURIComponent(queryStr)
      queryStr = window.decodeURIComponent(queryStr)
    }
    if (window.atob) {
      try {
        queryStr = window.atob(queryStr)
      } catch (e) {
        queryStr = ''
      }
    }
    if (window.decodeURIComponent) {
      queryStr = window.decodeURIComponent(queryStr)
    }
    const strArr = queryStr.split('&').filter(item => item)
    const queryObj = {}
    for (let i = 0, len = strArr.length; i < len; i++) {
      const match = strArr[i] && strArr[i].match(/^(.+?)=(.+)$/)
      if (match === null) {
        continue
      }
      const val = match[2]
      // 'true'或者'false'字符串会转为Boolean类型
      queryObj[match[1]] = (val === 'true' || val === 'false') ? JSON.parse(val) : val
    }
    return queryObj
  },
  // 生成Base64参数,@params Object, return String
  generateQuery (params) {
    if (typeof params !== 'object') {
      return ''
    }
    let queryStr = Object.keys(params).reduce((acc, cur) => {
      return `${acc}${acc ? '&' : ''}${cur}=${params[cur]}`
    }, '')
    if (!queryStr) {
      return ''
    }
    if (window.encodeURIComponent) {
      queryStr = window.encodeURIComponent(queryStr)
    }
    if (window.btoa) {
      queryStr = window.btoa(queryStr)
    }
    if (window.encodeURIComponent) {
      queryStr = window.encodeURIComponent(queryStr)
    }
    return queryStr
  }
}

使用方式

1.编码

urlParams.generateQuery({
  id: 123,
  des: 'hello world',
  isTest: true
})

此方法创建一个base-64编码的ASCII字符串aWQlM0QxMjMlMjZkZXMlM0RoZWxsbyUyMHdvcmxkJTI2aXNUZXN0JTNEdHJ1ZQ%3D%3D,然后附加到跳转的url参数后面就行,如http://xxxx/index.html?urlParams=aWQlM0QxM...
注:如不需要参数名urlParams=,需要修改上面代码中的第9行以便匹配到参数字符串

2.解码

假设当前页面url参数是经过上面步骤生成的,如http://xxxx/index.html?urlParams=aWQlM0QxM...,则可通过下续方式获得参数(已对Boolean做特殊处理,上面代码第36行)

const query = urlParams.getQuery()
console.log(query); // {id: "123", des: "hello world", isTest: true}