我如何执行一些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')?
}
当前回答
有点像@Hossein Hajizadeh alerady说的,不过更详细:
有一个替代eval()的方法。
函数setTimeout()被设计为在毫秒间隔后执行一些东西,而要执行的代码恰好格式化为字符串。
它是这样工作的:
ExecuteJavascriptString ();//只是为了运行它 ExecuteJavascriptString()函数 { Var s = "alert('hello')"; setTimeout (s, 1); }
1表示它将在执行字符串前等待1毫秒。
这可能不是最正确的方法,但它确实有效。
其他回答
eval(s);
但如果你从用户那里获取数据,这可能是危险的,尽管我想如果他们自己的浏览器崩溃了,那是他们的问题。
使用eval函数,比如:
eval("my script here");
对于使用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.
不确定这是不是作弊:
window.say = function(a) { alert(a); };
var a = "say('hello')";
var p = /^([^(]*)\('([^']*)'\).*$/; // ["say('hello')","say","hello"]
var fn = window[p.exec(a)[1]]; // get function reference by name
if( typeof(fn) === "function")
fn.apply(null, [p.exec(a)[2]]); // call it with params
试试这个:
var script = "<script type='text/javascript'> content </script>";
//using jquery next
$('body').append(script);//incorporates and executes inmediatelly
就我个人而言,我没有测试它,但似乎可以工作。