Using JavaScript Actions

Overview

If a more advanced interaction is required to set up or test your site, you can execute JavaScript in the context of your site.

How to use a JavaScript action

To add a JavaScript action to your test:

  1. Add a comment action step
  2. Enter rf_js_execute: followed by your JavaScript function in the comment section.

The JavaScript function should take one of the following forms, and always return an object with string keys and simple (int/string/float/bool values). Async functions will be automatically waited for.

rf_js_execute: (vars) => {return {"a_number": 5}}
rf_js_execute: async (vars) => {
	return {"async": "functions are ok too"}
}

You can reference data from a previous rf_js_execute step by inspecting the vars variable.

This step will pass as long as the JavaScript is valid and does not raise any exceptions. You can throw to cause the step to fail.

Note: JavaScript executes in the context of the current page, which means it is subject to CORS and any other restrictions the browser has in place.

Examples:

Output the page href in the test execution Console:

rf_js_execute: (vars) => document.location.href

Extract the current URL to a variable

rf_js_execute: (vars) => { return {"current_url": document.location.href}}

{{rainforest.var.current_url}} is now available to use in Fill, Type, Navigate, or future JS actions.

Make an API call and capture the response:

The following will make a GET request, and it pulls out the slideshow title into {{rainforest.var.title}}.

rf_js_execute: async (vars) => {  
  let response = await fetch("<https://httpbin.org/json>", {  
    method: "GET",  
    headers: {  
      "Accept": "application/json",  
    }  
  });  
  let data = await response.json();

  return {  
    "title": data["slideshow"]["title"],  
  }  
}

Update a count between steps

Run a comment JS action with the following:

rf_js_execute: (vars) => { return {"count": 6} }

If you use {{rainforest.vars.count}} in a Fill action, it will return 6.

Run a second comment action with the following:

rf_js_execute: (vars) => { return {"count": vars["count"] + 1} }

{{rainforest.vars.count}} will now return 7.



If you have any questions or suggestions for additional commands, reach out to us at [email protected].