Best way to safely read query string parameters?

前端 未结 5 1729
余生分开走
余生分开走 2020-12-30 16:58

We have a project that generates a code snippet that can be used on various other projects. The purpose of the code is to read two parameters from the query string and assig

5条回答
  •  爱一瞬间的悲伤
    2020-12-30 17:33

    Don't use escape and unescape, use decodeURIComponent. E.g.

    function queryParameters(query) {
      var keyValuePairs = query.split(/[&?]/g);
      var params = {};
      for (var i = 0, n = keyValuePairs.length; i < n; ++i) {
        var m = keyValuePairs[i].match(/^([^=]+)(?:=([\s\S]*))?/);
        if (m) {
          var key = decodeURIComponent(m[1]);
          (params[key] || (params[key] = [])).push(decodeURIComponent(m[2]));
        }
      }
      return params;
    }
    

    and pass in document.location.search.

    As far as turning < into <, that is not sufficient to make sure that the content can be safely injected into HTML without allowing script to run. Make sure you escape the following <, >, &, and ".

    It will not guarantee that the parameters were not spoofed. If you need to verify that one of your servers generated the URL, do a search on URL signing.

提交回复
热议问题