我如何执行一些JavaScript是一个字符串?
function ExecuteJavascriptString()
{
var s = "alert('hello')";
// how do I get a browser to alert('hello')?
}
我如何执行一些JavaScript是一个字符串?
function ExecuteJavascriptString()
{
var s = "alert('hello')";
// how do I get a browser to alert('hello')?
}
当前回答
试试这个:
var script = "<script type='text/javascript'> content </script>";
//using jquery next
$('body').append(script);//incorporates and executes inmediatelly
就我个人而言,我没有测试它,但似乎可以工作。
其他回答
eval函数将对传递给它的字符串求值。
但是eval的使用是超级危险和缓慢的,所以要谨慎使用。
如下所示使用eval。Eval应该谨慎使用,一个关于“Eval is evil”的简单搜索应该会抛出一些指针。
function ExecuteJavascriptString()
{
var s = "alert('hello')";
eval(s);
}
使用eval()。
W3学校评估之旅。网站有一些有用的例子的评估。Mozilla文档详细介绍了这一点。
你可能会得到很多关于安全使用的警告。不允许用户向eval()中注入任何东西,因为这是一个巨大的安全问题。
您还需要知道eval()具有不同的作用域。
同时使用eval和创建一个新函数来执行javascript会带来很多安全风险。
const script = document.createElement("script");
const stringJquery = '$("#button").on("click", function() {console.log("hit")})';
script.text = stringJquery;
document.body.appendChild(script);
我更喜欢这个方法来执行我作为字符串接收的Javascript。
对于使用node和关心eval()上下文含义的用户,nodejs提供了vm。它创建了一个V8虚拟机,可以在一个单独的上下文中沙盒代码的执行。
更进一步的是vm2,它强化vm,允许vm运行不受信任的代码。
https://nodejs.org/api/vm.html -正式的nodejs/vm https://github.com/patriksimek/vm2 -扩展vm2
const vm = require('vm');
const x = 1;
const sandbox = { x: 2 };
vm.createContext(sandbox); // Contextify the sandbox.
const code = 'x += 40; var y = 17;';
// `x` and `y` are global variables in the sandboxed environment.
// Initially, x has the value 2 because that is the value of sandbox.x.
vm.runInContext(code, sandbox);
console.log(sandbox.x); // 42
console.log(sandbox.y); // 17
console.log(x); // 1; y is not defined.