Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unable to run with eval #563

Open
venukbh opened this issue Sep 14, 2022 · 1 comment
Open

Unable to run with eval #563

venukbh opened this issue Sep 14, 2022 · 1 comment

Comments

@venukbh
Copy link

venukbh commented Sep 14, 2022

The Library is not working when loaded with eval to use it inside postman or similar kind of apps.

https://stackoverflow.com/questions/73711777/unable-to-load-and-eval-javascript-code-in-postman-pre-request

@somejeff
Copy link
Contributor

somejeff commented Nov 4, 2022

@victorquinn I was looking into this out of curiosity, because I use Postman as well, but never thought of using Chance in the pre-requests.

Root cause:

this.Chance and this.chance are defined manually in various ways at the end of the file (CommonJS, AMD, importScripts and window). The postman environment doesn't have any of these, including a window object, but it does have a this reference to a context.

Possible Solution:

Passing this into the function and binding to it, resolves the issue.

Replacing the window binding

Browsers today have an object called globalThis (See MDN & Can I Use)

This means that instead of this block chance.js#L7918-L7921:

    // If there is a window object, that at least has a document property,
    // instantiate and define chance on the window
    if (typeof window === "object" && typeof window.document === "object") {
        window.Chance = Chance;
        window.chance = new Chance();
    }

it could be replaced with a globalThis binding. For Postman (and that one individual left using IE11), we also pass in this into the IIFE

(function (t) {

/* Lines 8 - 7914 */


   // If there is a globalThis object (which is typically window), define chance
    // otherwise set it to this
    (t="undefined"!=typeof globalThis?globalThis:t||self).Chance = Chance;
    (t="undefined"!=typeof globalThis?globalThis:t||self).chance = new Chance();

})(this);

Test results

  • Ava Tests are not affected. (uses globalThis)
  • Browsers not affected
  • Postman works
  • Haven't tried Node, but since exports.Chance = Chance is still there, I don't see why it wouldn't work.

P.S. You don't have to replace the window code, you could leave it there and simple add the passing of this to the IIFE and have a few lines to handle this. It just sets window.Chance then this.Chance (which is window)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants