0

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:

  • Is this even possible to do using just javascript?
  • 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?
Mukul Gupta
  • 2,310
  • 3
  • 24
  • 39

1 Answers1

2

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.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • "which also has the advantage that you can kill and restart it when it hangs." Actually with site isolation you can now do the same with iframes in most modern browsers (all but Safari). Also, I think https://github.com/tc39/proposal-shadowrealm is doing something in that area, though I didn't really check it yet. – Kaiido Sep 20 '22 at 22:28
  • Could you describe the web worker approach? If the web worker also uses `eval` when it receives a message containing the snippet, would it not suffer from the same limitation? – Mukul Gupta Sep 21 '22 at 22:22
  • @MukulGupta In a web worker you could use [global eval](http://perfectionkills.com/global-eval-what-are-the-options/) without the usual bad consequences. If you require `let`/`const` redeclarations like in the devtools console, that's only possible with nested scopes and shadowing, using [the hack](https://stackoverflow.com/questions/67322922/context-preserving-eval/67394423) I had linked – Bergi Sep 22 '22 at 00:03