gpt4 book ai didi

javascript - 从 HTTP 请求执行 JavaScript 函数

转载 作者:行者123 更新时间:2023-12-02 13:50:19 25 4
gpt4 key购买 nike

您好,我正在尝试从 HTTP Get 请求中获取一个函数。但是我无法使脚本运行

我的代码是:

<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript">

window.launch = function(url, has_credits) {
if (has_credits != "True"){
if (!confirm(con_str)){
window.close();
}
}
document.getElementById("waiting_msg").innerHTML = "Loading..."
location.href = url;
};

var xmlHttp = new XMLHttpRequest();
theUrl = 'http://127.0.0.1:8000/game/launch/?provider=XXX&game=7bal_tie&token=50c63444b85cdadf5e4b9285c2be5444&jsonp=launch'
xmlHttp.open( "GET", theUrl, true );
xmlHttp.send( null );
//
// The script that will trigger the function
//
</script>
</body>
</html>

请求的返回结果为

launch("http://my-url.com","False");

这应该将我重定向到上述网址。我希望 javascript 有一个内置函数,可以像这样轻松运行它

func(xmlHttp.response);

然后只会触发该函数,但我找不到任何函数,并且 eval 没有为我锻炼

最佳答案

eval 应该可以工作,但对于原型(prototype)之外的任何东西来说这都是非常糟糕的主意。您尚未设置 responseType,但我认为您需要 responseText 而不是 response。我不确定响应类型是什么,但它可能是缓冲区或类似的东西,这不是您想要的。

你可以这样做:

function reqListener () {
if (xmlHttp.status !== 200) return;
eval(this.responseText);
}

xmlHttp.addEventListener("load", reqListener);

但是,使用eval 并不是一个好主意。假设您将 API 响应更改为此:

{
"func": "launch",
"params": ["http://my-url.com", "False"]
}

然后你可以这样做:

function reqListener () {
if (xmlHttp.status !== 200) return;
var respObj = JSON.parse(this.responseText);
window[respObj.func].apply(window, respObj.params);
}

xmlHttp.addEventListener("load", reqListener);

这仍然不理想,因为它可用于在窗口对象上执行任意代码,但它比直接使用 eval 好一点,因为它限制了漏洞的范围。

这个问题的真正答案是,您不应该让您的 JavaScript 暴露于远程代码执行的可能性。因此,不要在生产中使用此代码,而是重新设计 API。

关于javascript - 从 HTTP 请求执行 JavaScript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41036221/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com