Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JavaScript 中使用 new Function 执行字符串拼接表达式 #6

Open
zwhu opened this issue Oct 12, 2015 · 0 comments
Open

JavaScript 中使用 new Function 执行字符串拼接表达式 #6

zwhu opened this issue Oct 12, 2015 · 0 comments

Comments

@zwhu
Copy link
Owner

zwhu commented Oct 12, 2015

最近在用 node 学写爬虫,也可以叫模拟登陆,遇到某个网站在返回的 HTML 中插入了一个生成页面token的script。

这个HTML的结构大概类似

<!Doctype html>
<html>
    <head></head>
    <body>
        <div></div>
        <script>       
            (function (w) {
                w.token = (function () {
                    // ....
                    // 生成token

                return token;
                })();;
            })(window);
        </script>
    </body>
</html>

首先拿到这个页面,然后获取script标签的表达式字符串,剩下的事就是怎样执行表达式字符串,并获取token。

在此处的情景中用eval也是挺不错的选择,但是既然 JS 不推荐这种用法,那我们就换成 new Function 来做。

看下 new Function 的用法如下

new Function ([arg1[, arg2[, ...argN]],] functionBody)

new Function会返回一个函数。例如 fn = new Function('a', 'b', 'return a + b') 会返回一个函数对象

fn = function(a, b) {
    return a + b
}

so,我们可以使用 new Function 构造一个函数,用来执行获取到得表达式,并返回token。

    fn = new Function('window', functionBody + ';return window.token')
    var token = fn({})
    console.log(token)

构造的这个函数有个window形参,作为函数体中立即执行表达式的实参传入最内层的函数中。所以在最后执行的时候 return window.token 便会获得token 的内容。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant