I have such a function with imported module that I cannot edit
function create() {
const window = {}; // Normally initialized by JSDOM to make fake window
const appboy = require("@braze/web-sdk");
}
What I want is that appboy
sees the local window
from create
function.
I want to avoid globalThis.window
because of race conditions of create
function when run concurrently.
2
Answers
You can’t, unless
@braze/web-sdk
explicitly provides a way to do it. The variables available to code are determined by what’s in scope where that code is defined, not where it’s used from. Unless that module provides some way to pass it a value for this (which I’m guessing it doesn’t from the question), the only way to affect what it sees aswindow
is to create/overwrite a global, as that’s the only scope your code and the module have in common.Depending on the constraints you’re working under, one option might be to fork the module, add the necessary feature, and use that forked module in your code (perhaps even offering the original a pull request with the changes).
As I mentioned in the comment above, there exists a workaround where we can specify our own custom global context.
Node has native VM module that can sandbox scripts.
These sandboxed scripts can have it’s own context.
Here is an example how it works to point us to the right way.
Say we have a little script
Depending on environment it can either print out global
Window
object if we run it in browser or throw aRefferenceError
in Node.JS.With a help of
vm.createContext
we can create our ownwindow
and specify it to the script.Now all we need to attach our context to script and run it
The result of execution will be a
Fake window
text in our console.As a result of this quick example now we know that we can apply similar approach to the external node_modules.
I want to believe that this one will guide you to solution of the problem.