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.
Instead of using
eval, you can do:Output in Postman console (you can open it bottom right):
Explanation: I am not sure why, but I just couldn't get
evalto work. I suspect that it has to do with global scope of VM Postman is using (there is nowindowlike in browsers orgloballike in Node.js but apmglobal object).Function constructor acts similar to
evalfunction, 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.