Reputation: 223054
The ones that I'm aware of are eval
, Function
and setTimeout
. Even though setImmediate
reference doesn't mention that it can be called with string argument, I assume it will work the same way as setTimeout
in this regard.
What are the possible ways (including non-standard ones) to evaluate the code from a string in browsers?
Upvotes: 4
Views: 114
Reputation: 1075417
On browsers, the only ones I know are:
eval
Function
constructorsetTimeout
and related (setInterval
, non-standard setImmediate
)document.write
or similar)javascript:
pseudo-protocol on links and such (and then either clicking them artifically or inviting the user to do so)
Live:
eval("console.log('eval');");
(0,eval)("console.log('indirect eval');");
new Function("console.log('Function constructor');")();
setTimeout("console.log('setTimeout and such');", 0);
var script = document.createElement("script");
script.textContent = "console.log('script element');";
document.body.appendChild(script);
var link = document.createElement("a");
link.href = "javascript:console.log('javascript: pseudo-protocol');";
document.body.appendChild(link);
link.click();
var div = document.createElement("div");
div.setAttribute("onclick", "console.log('DOM0 event handler');");
document.body.appendChild(div);
div.click();
/* Or to be long-winded
div.dispatchEvent(new MouseEvent("click", {
view: window,
bubbles: true,
cancelable: true
}));
*/
Upvotes: 5
Reputation: 5260
non-standard one using immediate execution
<h1>
</h1>
<script></script>
$("script").html("(function(){$('h1').html('wow');})()");
There is also a non-standard way not mentioned so far here that is using wkhtmltopdf, in this way wkhtmltopdf myjscode.html all.pdf where myjscode.html is generated with fopen/cat or something taking string as argument. When pdf is executed, javascript is executed (https://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/js_api_reference.pdf), also javascript is executed server side (yes). This could seems non relevant but it has big implications on security. If we're going do a pdf based in part on user inputs with wkhtmltopdf we have this problem to keep in mind.
Upvotes: 2
Reputation: 47881
In addition to the methods mentioned in the other answers, in a browser you could do:
document.write('<script>doSomething()</script>');
const script = document.createElement('script');
script.src = 'data:text/javascript,' + encodeURIComponent('doSomething()');
document.body.appendChild(script);
Upvotes: 1