How do I execute some JavaScript that is a string?
function ExecuteJavascriptString()
{
var s = "alert('hello')";
// how do I get a browser to alert('hello')?
}
How do I execute some JavaScript that is a string?
function ExecuteJavascriptString()
{
var s = "alert('hello')";
// how do I get a browser to alert('hello')?
}
With the eval
function, like:
eval("my script here");
WARNING: Any malicious code contained within the string will be executed with the same privileges of your site, make absolutely sure you can trust the source.
You can execute it using a function. Example:
var theInstructions = "alert('Hello World'); var x = 100";
var F=new Function (theInstructions);
return(F());
The eval
function will evaluate a string that is passed to it.
But the use of eval
is super dangerous AND slow, so use with caution.
For users that are using node and that are concerned with the context implications of eval()
nodejs offers vm
. It creates a V8 virtual machine that can sandbox the execution of your code in a separate context.
Taking things a step further is vm2
which hardens vm
allowing the vm to run untrusted code.
https://nodejs.org/api/vm.html - Official nodejs/vm
https://github.com/patriksimek/vm2 - Extended 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.
Try this:
var script = "<script type='text/javascript'> content </script>";
//using jquery next
$('body').append(script);//incorporates and executes inmediatelly
Personally, I didn't test it but seems to work.
Use eval().
W3 Schools tour of eval. Site has some usable examples of eval. The Mozilla documentation covers this in detail.
You will probably get a lot of warnings about using this safely. do NOT allow users to inject ANYTHING into eval() as it is a huge security issue.
You'll also want to know that eval() has a different scope.
new Function('alert("Hello")')();
I think this is the best way.
A bit like what @Hossein Hajizadeh alerady said, though in more detail:
There is an alternative to eval()
.
The function setTimeout()
is designed to execute something after an interval of milliseconds, and the code to be executed just so happens to be formatted as a string.
It would work like this:
ExecuteJavascriptString(); //Just for running it
function ExecuteJavascriptString()
{
var s = "alert('hello')";
setTimeout(s, 1);
}
1
means it will wait 1 millisecond before executing the string.
It might not be the most correct way to do it, but it works.
Checked this on many complex and obfuscated scripts:
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);
New Function and apply() together works also
var a=new Function('alert(1);')
a.apply(null)
Use eval as below. Eval should be used with caution, a simple search about "eval is evil" should throw some pointers.
function ExecuteJavascriptString()
{
var s = "alert('hello')";
eval(s);
}
If you want to execute a specific command (that is string) after a specific time - cmd=your code - InterVal=delay to run
function ExecStr(cmd, InterVal) {
try {
setTimeout(function () {
var F = new Function(cmd);
return (F());
}, InterVal);
} catch (e) { }
}
//sample
ExecStr("alert(20)",500);
I was answering similar question and got yet another idea how to achieve this without use of eval()
:
const source = "alert('test')";
const el = document.createElement("script");
el.src = URL.createObjectURL(new Blob([source], { type: 'text/javascript' }));
document.head.appendChild(el);
In the code above you basically create Blob, containing your script, in order to create Object URL (representation of File or Blob object in browser memory). Since you have src
property on <script>
tag, the script will be executed the same way as if it was loaded from any other URL.
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!');");
An extention of Stefan's answer:
//Executes immediately
function stringToFunctionAndExecute(str) {
let func = new Function(str);
return (func()); // <--- note the parenteces
}
//Executes when called
function stringToFunctionOnly(str) {
let func = new Function(str);
return func;
}
// -^-^-^- Functions -^-^-^- (feel free to copy)
// -v-v-v- Explanations -v-v-v- (run code to read easier)
console.log('STEP 1, this executes directly when run:')
let func_A = stringToFunctionAndExecute("console.log('>>> executes immediately <<<')");
console.log("STEP 2, and you can't save it in a variable, calling a() will throw an error, watch:")
try {
func_A();
} catch (error) {
console.log('STEP ERROR, see, it failed', error)
}
console.log('STEP 3, but this will NOT execute directly AND you can save it for later...')
let func_B = stringToFunctionOnly("console.log('>>> executes when called <<<')");
console.log("STEP 4, ...as you see, it only run when it's called for, as is done now:")
func_B();
console.log('STEP 5, TADAAAAA!!')
eval(s);
But this can be dangerous if you are taking data from users, although I suppose if they crash their own browser thats their problem.
Not sure if this is cheating or not:
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
One can use mathjs
Snippet from above link:
// evaluate expressions
math.evaluate('sqrt(3^2 + 4^2)') // 5
math.evaluate('sqrt(-4)') // 2i
math.evaluate('2 inch to cm') // 5.08 cm
math.evaluate('cos(45 deg)') // 0.7071067811865476
// provide a scope
let scope = {
a: 3,
b: 4
}
math.evaluate('a * b', scope) // 12
math.evaluate('c = 2.3 + 4.5', scope) // 6.8
scope.c
scope
is any object. So if you pass the global scope to the evalute function, you may be able to execute alert() dynamically.
Also mathjs is much better option than eval() because it runs in a sandbox.
A user could try to inject malicious JavaScript code via the expression parser. The expression parser of mathjs offers a sandboxed environment to execute expressions which should make this impossible. It’s possible though that there are unknown security vulnerabilities, so it’s important to be careful, especially when allowing server side execution of arbitrary expressions.
Newer versions of mathjs does not use eval() or Function().
The parser actively prevents access to JavaScripts internal eval and new Function which are the main cause of security attacks. Mathjs versions 4 and newer does not use JavaScript’s eval under the hood. Version 3 and older did use eval for the compile step. This is not directly a security issue but results in a larger possible attack surface.
Using both eval and creating a new Function to execute javascript comes with a lot of security risks.
const script = document.createElement("script");
const stringJquery = '$("#button").on("click", function() {console.log("hit")})';
script.text = stringJquery;
document.body.appendChild(script);
I prefer this method to execute the Javascript I receive as a string.
This method avoids use of potentially-risky eval, provides callable functions, uses strict mode on the expression evaluator for extra reliability, and less verbose than other answers.
execute a string command
function string_cmd(sCmd) {
new Function(sCmd)();
}
evaluate a string expression
function string_exp(sCmd) {
return Function(
`'use strict';
return (${sCmd})`
)();
}
usage:
const result = string_exp("2+2");
string_cmd("alert(result)");
eval(s);
Remember though, that eval is very powerful and quite unsafe. You better be confident that the script you are executing is safe and unmutable by users.