gpt4 book ai didi

javascript - 具有无限循环的函数

转载 作者:行者123 更新时间:2023-12-02 20:53:46 24 4
gpt4 key购买 nike

我有一个文本区域,当我使用

运行它时,用户可以在其中输入任何js代码

const userCode = "while(true);"
const func = new Function("", userCode);

func();

网页卡住了,我能做什么?可以使用WebWorker吗?

最佳答案

工作人员是可能的,但工作人员无法访问脚本编写者通常希望在前端访问的许多内容。考虑将代码放入沙盒 iframe 中 - 这不仅可以使顶部选项卡保持响应并允许访问更多对象,而且也更加安全。这是 Stack Snippets 和网站上其他实时代码编辑器使用的技术。

获取用户的代码,并将其发送到迷你后端,该后端获取用户的脚本并将其插入 <script>标签:

textarea {
display: block;
}
<form target=iframe method=post action="https://stacksnippets.net/js">
<button>Run</button>
<textarea name="js" rows=4 cols=100>console.log('user should insert code into this textarea');</textarea>
</form>
<iframe name=iframe sandbox="allow-scripts allow-popups"></iframe>

或者,对于无限循环:

textarea {
display: block;
}
<form target=iframe method=post action="https://stacksnippets.net/js">
<button>Run</button>
<textarea name="js" rows=4 cols=100>while (true);</textarea>
</form>
<iframe name=iframe sandbox="allow-scripts allow-popups"></iframe>

上述内容将消耗大量资源,但您会看到 Stack Overflow(和代码片段)页面保持响应。只有内部 iframe 会因无限循环而无响应。

在这里,所有这些 https://stacksnippets.net/js它的作用是从 js 获取代码并将其插入到 HTML 响应中:

<!DOCTYPE html>
<html>
<head>
<style>

</style>
<script src="/scripts/snippet-javascript-console.min.js?v=1"></script>
</head>
<body>
test
<script type="text/javascript">
// USER'S CODE GOES HERE
</script>
</body>
</html>

让你的后端做同样的事情。

关于javascript - 具有无限循环的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61540185/

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