这段 JavaScript 代码安全吗?

发布于 2024-11-28 08:56:02 字数 520 浏览 1 评论 0原文

我在网上找到了以下JS。

它是一个获取 url 参数值的函数。

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() 函数时,我总是想:哎呀!

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

附带说明:如果您认为这个函数很糟糕并且有更好的选择,请毫不犹豫地分享:)

上面的函数使用真实的 url,但我只需要解析包含 URL 的字符串。

I have found the following JS on the web.

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];
}

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 :)

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

甩你一脸翔 2024-12-05 08:56:02

您在函数中看到的 .exec() 不是窗口的,而是 RegExp 对象的。

所以使用起来完全没问题。

The .exec() you see in your function is not of the window but of the RegExp object.

So it is perfectly fine to use.

豆芽 2024-12-05 08:56:02

我不会将 Regexp execeval 混淆。有点笨重,但应该可以用。

I wouldn't confuse a Regexp exec with an eval. A little clunky but it should work.

日久见人心 2024-12-05 08:56:02

Regexp#exec 是安全的,尽管不是一个非常好的界面。

补充:如果您认为这个功能很糟糕并且有更好的选择,请毫不犹豫地分享:)

yeeep :-)

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

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

然后:

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

您没有转义足够多的字符,无法将它们放入正则表达式中并让它们代表它们的字面意思。请参阅此问题以获取更可靠的替代方案。

无论如何,这种正则表达式黑客攻击仍然不是解析 URL/查询字符串的好方法。这不能正确处理 ;%-编码,或 + 空格,并且可能会因 URL 中其他地方的参数相似而出错。

相反,我们首先获取查询字符串本身。如果您有链接或位置对象,则可以从 .search 属性获取它。如果您只有一个字符串 URL,则可以将其转换为链接对象以可靠地获取此内容:

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

现在您可以通过删除前导 ? 并拆分 & 将其解析为> 或 ;,然后将 URL 解码的结果放入 JS 对象中:

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;
}

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

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 舞蹈,在查找中返回单个字符串值而不是列表。

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 :)

yeeep :-)

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

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('\\[').

Then:

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.

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.

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;
}

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文