decodeURIComponent在解析浏览器参数中含有%时报错处理

12961次浏览

前言

之前有篇文章,介绍了encodeURIComponent 的一些用法,encodeURIComponent是对浏览器参数编码,decodeURIComponent是对齐进行解码。最近在使用decodeURIComponent的时候,发现浏览器参数中含有特殊符号%,会导致decodeURIComponent等解码报错。今天就简单分享一下如何处理这个问题。

现象阐述

例如如下:

https://www.haorooms.com/?param=haorooms%E5%8D%9A%E5%AE%A2%E5%A5%BD%E8%AF%84%E7%8E%8790%

enter image description here

decodeURIComponent(param)

会报错

浏览器中的不安全字符

不安全符号 解释
空格 Url在传输的过程,或者用户在排版的过程,或者文本处理程序在处理Url的过程,都有可能引入无关紧要的空格,或者将那些有意义的空格给去掉
引号以及<> 引号和尖括号通常用于在普通文本中起到分隔Url的作用
# 通常用于表示书签或者锚点
% 百分号本身用作对不安全字符进行编码时使用的特殊字符,因此本身需要编码
{}\^[]`~ 某一些网关或者传输代理会篡改这些字符

解决方案

首页要对param中的不安全字符进行转译,转译完毕再进行编码和解码 ps(对于浏览器默认编码了的,如haorooms%E5%8D%9A%E5%AE%A2%E5%A5%BD%E8%AF%84%E7%8E%8790%,不能再进行字符替换了。)

// 对查询关键字中的特殊字符进行编码
  encodeSearchKey(key) {
    const encodeArr = [{
      code: '%',
      encode: '%25'
    }, {
      code: '?',
      encode: '%3F'
    }, {
      code: '#',
      encode: '%23'
    }, {
      code: '&',
      encode: '%26'
    }, {
      code: '=',
      encode: '%3D'
    }];
    return key.replace(/[%?#&=]/g, ($, index, str) => {
      for (const k of encodeArr) {
        if (k.code === $) {
          return k.encode;
        }
      }
    });
  },

对于已经被浏览器编译了的,可以采用如下方式,避免报错

方法一:

function decodeURIComponentSafe(uri, mod) {
    var out = new String(),
        arr,
        i = 0,
        l,
        x;
    typeof mod === "undefined" ? mod = 0 : 0;
    arr = uri.split(/(%(?:d0|d1)%.{2})/);
    for (l = arr.length; i < l; i++) {
        try {
            x = decodeURIComponent(arr[i]);
        } catch (e) {
            x = mod ? arr[i].replace(/%(?!\d+)/g, '%25') : arr[i];
        }
        out += x;
    }
    return out;
}

方法二: 采用try catch捕获

function decodeURIComponentSafely(uri) {
    try {
        return decodeURIComponent(uri)
    } catch(e) {
        console.log('URI Component not decodable: ' + uri)
        return uri
    }
}

小结

彻底解决这个问题,浏览器上面先encode编码再decode解码就没有问题,不编码的话,只能按照上面方式解决!其他无解!

浏览器参数中,尽量不要使用不安全符合,我们写代码的时候,为了严谨,可以使用decodeURIComponentSafe 函数,或者采用try catch捕获,避免因为浏览器有不安全符合引发代码报错!

欢迎访问haorooms前端博客,haorooms前端博客欢迎您!

相关文章: