Mukul Gupta
Mukul Gupta

Reputation: 2425

Use same javascript execution context for multiple eval functions

I'm building a project that allows users to add and annotate multiple <textarea> inputs with small javascript code snippets and run them individually using browser's javascript runtime. Imagine it to be similar to jupyter notebooks for client-side javascript.

However, I'm facing issues trying to share the same javascript execution context between the two snippets.

Imagine the first snippet to be:

let x = 5;

And the second snippet to be:

let y = x + 5;

I run the individual snippets using eval. However, as expected the second snippet complaints of x being undefined because it's not found in the same function scope.

We don't have the same behaviour in browser's DevTools (Javascript Console or Scripts) and they continue to share the same global execution context.

Questions:

Upvotes: 0

Views: 113

Answers (1)

Bergi
Bergi

Reputation: 665080

Is this even possible to do using just javascript?

Yes, something like that is possible, but I really wouldn't recommend that approach. Rather create an <iframe> and inject global <script> tags inside it, or get a web worker to run the notebook code - which also has the advantage that you can kill and restart it when it hangs.

The browser is able to share global execution context in its Developer Tools Console. Are there any APIs that can utilise this functionality? Is the browser able to do so because it uses some native functionalities of the browser?

Many tools can access that browser API, e.g. debugger integrated in IDEs. But yes, this is a native browser API, and it is not available from the javascript running inside a page.

Upvotes: 2

Related Questions