我如何执行一些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')?
}
当前回答
该方法避免使用潜在风险的eval,提供了可调用的函数,对表达式求值器使用严格模式以获得额外的可靠性,并且比其他答案更简洁。
执行字符串命令
function string_cmd(sCmd) {
new Function(sCmd)();
}
求字符串表达式的值
function string_exp(sCmd) {
return Function(
`'use strict';
return (${sCmd})`
)();
}
用法:
const result = string_exp("2+2");
string_cmd("alert(result)");
https://codepen.io/johnaweiss/pen/mdKpyZL
其他回答
function executeScript(source) {
var script = document.createElement("script");
script.onload = script.onerror = function(){ this.remove(); };
script.src = "data:text/plain;base64," + btoa(source);
document.body.appendChild(script);
}
executeScript("alert('Hello, World!');");
如果你想在后面执行一个特定的命令(即字符串) 特定的时间 - cmd=你的代码 —InterVal=运行延迟时间
function ExecStr(cmd, InterVal) {
try {
setTimeout(function () {
var F = new Function(cmd);
return (F());
}, InterVal);
} catch (e) { }
}
//sample
ExecStr("alert(20)",500);
检查了许多复杂和混乱的脚本:
var js = "alert('Hello, World!');" // put your JS code here
var oScript = document.createElement("script");
var oScriptText = document.createTextNode(js);
oScript.appendChild(oScriptText);
document.body.appendChild(oScript);
eval函数将对传递给它的字符串求值。
但是eval的使用是超级危险和缓慢的,所以要谨慎使用。
我正在回答类似的问题,并得到了另一个想法,如何在不使用eval()的情况下实现这一点:
const source = "alert('test')";
const el = document.createElement("script");
el.src = URL.createObjectURL(new Blob([source], { type: 'text/javascript' }));
document.head.appendChild(el);
在上面的代码中,您基本上创建了Blob,其中包含您的脚本,以便创建Object URL(浏览器内存中的文件或Blob对象的表示)。由于你在<script>标签上有src属性,脚本将以与从任何其他URL加载相同的方式执行。