Search code examples
javascriptpostmanpostman-pre-request-scriptminifiedjs

Postman - calling function in external JS file - 'x is not defined'


Other posts have dealt with this question, but I continue to be unable to apply this myself.

I have a Postman pre-script test.

I am trying to call an encryption function defined in http://some-server:port/lib/forge/forge.min.js

The code calls the code like this:

let pubKey = forge.pki.publicKeyFromPem(atob(publicKey));
...
let .... = forge.util.encodeUtf8(data));
let ... = forge.util.encode64(text);
...

I tried the eval trick, putting the whole code into a variable.

var code = pm.collectionVariables.get('forge.min.js');
eval(code);

The resulting error was:

ReferenceError: forge is not defined

The code variable has the whole block of minified Javascript.


Solution

  • Instead of using eval, you can do:

    (new Function(code))();
    
    console.log(forge);
    

    Output in Postman console (you can open it bottom right):

    {
      aes:{...}
      asn1:{...}
      cipher:{...}
      ...
    }
    

    Explanation: I am not sure why, but I just couldn't get eval to work. I suspect that it has to do with global scope of VM Postman is using (there is no window like in browsers or global like in Node.js but a pm global object).

    Function constructor acts similar to eval function, but encloses it into its own inner scope, so outer variables cannot be accessed. You can read more here.

    The syntax is a bit confusing, but put in words, it creates a new function and then calls it. There must an extra pair of parentheses around new Function(...) since 'function call' operator (the () at the end) binds stronger than the 'new' operator.