2

I am executing a JS script using vm module in browser like this with details below.

vm.runInNewContext(codeToEval, sandboxObject);

setTimeout, setInterval and other interval built in methods do not work, even if I expose them in sandboxObject created using vm.createContext({setTimeout})

console.log('start');
setTimeout(()=> {
     console.log('hello timeout');
 }, 2000);

 console.log('end');

output:

start
end

It is to be noted that when I add .bind(this) , then timeout works and breaks at that line saying .bind is not a function.

console.log('start');
setTimeout(()=> {
     console.log('hello timeout');
 }, 2000).bind(this);

 console.log('end');

output:

start
hello timeout
// and an error in console saying setTimeout(...).bind is not a function
// and end is not printed

Chrome 70

Platform Ubuntu 18.04

V8

ahmadalibaloch
  • 5,851
  • 2
  • 50
  • 59
  • I ended up creating my own custom `setTimeout`, explained here : https://gist.github.com/ahmadalibaloch/6c7d70244c83b90aa77bb83fa28cd0df – ahmadalibaloch Sep 11 '19 at 17:31

1 Answers1

-1

Put setTimeout and other context dependencies into into sandboxObject and execute code like this

let executionContext = {
  setTimeout,
}
vm.createContext(executionContext);
vm.runInContext(code, executionContext)