这个 JavaScript 代码安全吗? [英] Is this JavaScript code safe?

查看:30
本文介绍了这个 JavaScript 代码安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在网上找到了以下 JS.

I have found the following JS on the web.

获取url参数值的函数.

It is a function to get url params values.

function get_url_param(param) {
  param = param.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+param+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec(window.location.href);
  if( results == null )
    return '';
  else
    return results[1];
}

但是当我看到 exec() 函数时,我总是想:Eeek!

However always when I see a exec() function I think: Eeek!

所以我的问题是:它安全吗?

So my question is: is it safe?

边注:如果您认为此功能很糟糕并且有更好的选择,请不要犹豫,分享 :)

Side bet: If you think this function sucks and have a better option don't hesitate to share :)

上面的函数使用了真实的 url 但我只需要解析一个包含 URL 的字符串.

The above function uses the real url but I only need to parse a string which contains an URL.

推荐答案

Regexp#exec 是安全的,虽然不是一个很好的界面.

Regexp#exec is safe, albeit not a very nice interface.

边注:如果您认为此功能很糟糕并且有更好的选择,请不要犹豫,分享 :)

Side bet: If you think this function sucks and have a better option don't hesitate to share :)

是的 :-)

param = param.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");

这不使用 g 局部正则表达式,因此您只替换每个括号的一个实例;field[][] 不起作用.此外,您不需要字符组... param.replace(/\[/g, '\\[') 会起作用.或者,非正则表达式替换习惯用法,param.split('[').join('\\[').

This doesn't use a global regexp so you are only replacing one instance of each bracket; field[][] wouldn't work. Also you don't need the character group... param.replace(/\[/g, '\\[') would have worked. Or, the non-regexp replacement idiom, param.split('[').join('\\[').

那么:

var regexS = "[\\?&]"+param+"=([^&#]*)";

您没有转义几乎足够的字符来将它们放入正则表达式并让它们表示它们的字面意思.请参阅这个问题以获取更安全的替代方案.

you're not escaping nearly enough characters to be able to drop them into a regexp and have them mean their literal selves. See this question for a more watertight alternative.

无论如何,这种 regex hacking 仍然不是解析 URL/查询字符串的好方法.这不能正确处理 ;%-encoding 或 + 空格,并且它可能会因 URL 中其他地方的参数相似而跳闸.

Anyway this kind of regex hacking still isn't a good way of parsing URLs/query strings. This doesn't deal properly with ; or %-encoding, or + for space, and it may trip on parameter lookalikes elsewhere in the URL.

相反,让我们首先自己获取查询字符串.如果您有链接或位置对象,则可以从 .search 属性中获取.如果你只有一个字符串 URL,你可以把它变成一个链接对象来可靠地得到这个:

Instead, let's first get the query string on its own. If you have a link or location object, you can get it from the the .search property . If you only have a string URL, you can turn it into a link object to get this reliably:

function getQueryString(url) {
    var a= document.createElement('a');
    a.href= url;
    return a.search;
}

现在您可以通过删除前导 ? 将其解析为&;,然后删除 URL 解码的结果进入一个 JS 对象:

Now you can parse it into by dropping the leading ?, splitting on & or ;, then dropping the URL-decoded results into a JS Object:

function parseQuery(query) {
    var lookup= {};
    var params= query.slice(1).split(/[&;]/);
    for (var i= 0; i<params.length; i++) {
        var ix= params[i].indexOf('=');
        if (ix!==-1) {
            var name= decodeURIComponent(params[i].slice(0, ix));
            var value= decodeURIComponent(params[i].slice(ix+1));
            if (!(name in lookup))
                lookup[name]= [];
            lookup[name].push(value);
        }
    }
    return lookup;
}

这使得查找参数变得容易:

This makes it easy to look up parameters:

var url= 'http://www.example.com/?a=b&c=d&c=%65;f[]=g#h=i';
var pars= parseQuery(getQueryString(url));

alert(pars.a);      // ['b']
alert(pars.c);      // ['d', 'e']
alert(pars['f[]']); // ['g']
alert('h' in pars); // false

如果您不需要为一个参数读取多个值,您可以只执行 lookup[name]= value 而不是 if...[]...push 跳舞,在查找中返回单个字符串值而不是列表.

If you don't need to read multiple values for a parameter, you could just do lookup[name]= value instead of the if...[]...push dance, to return single string values in the lookup instead of lists.

这篇关于这个 JavaScript 代码安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆