skip to Main Content

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


  1. 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 as window 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).

    Login or Signup to reply.
  2. 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

    console.log(window)
    

    Depending on environment it can either print out global Window object if we run it in browser or throw a RefferenceError in Node.JS.

    With a help of vm.createContext we can create our own window and specify it to the script.

    const vm = require('node:vm');  
    
    // plain object for our purposes
    const customGlobal = {
      window: 'Fake window',
      console //console should be passed to let our script option to use it
    };  
    
    // plain string with valid js script
    const code = 'console.log(window)';  
    
    // here we wrap code into executable environment
    const script = new vm.Script(code);
    
    // creating context from our plain object
    const context = vm.createContext(customGlobal);
    

    Now all we need to attach our context to script and run it

    script.runInContext(context);
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search