Run JavaScript in JMeter or Load External JavaScript in JMeter: In this tutorial, you will learn how to run JavaScript in JMeter or loading/run the JavaScript loading from external sources and you can use evaluated values and make use of them in your script.

Why do we need to use JavaScript in JMeter?

In some scenarios like payment steps or some form submitted in the application will use some front-end encryption to encrypt the data sent from the browser.

While creating a performance script we should send the correlated and parameter data in the same way the browser is sending.

In such cases, we need to encrypt the post data using JMeter before sending it to the server

How do we Run JavaScript/ External JavaScript in JMeter?

To run JavaScript in Jmeter we have JSR223 Sampler where we can execute code of groovy, Java, JavaScript, Beanshell, etc.

  • JSR223 is available as Individual Sampler, Post Processor, and Pre Processor for a Sampler

How to Run Sample JavaScript Code in JMeter?

  • Add JSR223 Sampler to your ThreadGroup
  • Then write the below code to JSR223 Sampler
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min) ) + min;
}
var a = getRndInteger(10,100);
log.info("Random variable:"+a);
vars.put("randomVaraible",a);

Run-JavaScript-in-Jmeter-or-Load-External-JavaScript-in-Jmeter

  • Add Debug Sampler to see the executed results
  • After executing the script below will be the output

Run-JavaScript-in-Jmeter-Load-External-JavaScript

How to Load the External JavaScript File in JMeter?

JMeter will support the Rhino Framework JavaScript execution. In rhino to load a JavaScript file, we need to use the load function to get the file or code

  • The Below code will help you to load the external crypto.js for crypto encryption
/* URL Loading*/
load("https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/crypto-js.js");
/*for loading file from local of your jmeter place script in bin folder then 
* load("file name with extension");
*/ 
var myString = "encrypt my code";
var myPassword = "myPassword";
/*PROCESS*/
var encrypted = CryptoJS.AES.encrypt(myString, myPassword);
var decrypted = CryptoJS.AES.decrypt(encrypted, myPassword);
log.info(""+encrypted); vars.put("encryptedValue",encrypted);
  • After Executing the Code below will be the output

Run-JavaScript-in-Jmeter

  • After Executing the code will is the output

Load-External-JavaScript-in-Jmeter

Note: Document and Window objects will not work in JMeter. Because we are not running our scripts in the browser.


Thanks,

Also Read: How to Run JMeter Samplers Defined Percentage

Also Read: Beanshell Assertion in JMeter

 

Run JavaScript in JMeter or Load External JavaScript in JMeter

Leave a Reply

Your email address will not be published. Required fields are marked *