Using a Selenium JSON Script in Screenshot Tests

Applies to CrossBrowserTesting SaaS, last modified on November 26, 2020

You can use a Selenium script to position the browser to the page or state you want before taking a screenshot. This is very useful in capturing screenshots of pages that cannot be shown directly via a particular URL. Using the Selenium script, you can navigate to the proper page, enter information into certain fields, perform actions, etc. After this script is finished, the screenshot engine will produce a screenshot of this page.

Recording the Selenium script

The Selenium script needs to be in JSON format in order to work with our Screenshots system.

Here is an example of logging into our app

Notice the use of 3 different locators.

{
  "type": "script",
  "seleniumVersion": "2",
  "formatVersion": 2,
  "steps": [
    {
      "type": "get",
      "url": "https://app.crossbrowsertesting.com/login"
    },
    {
      "type": "setElementText",
      "locator": {
        "type": "xpath",
        "value": "//*[@id=\"inputEmail\"]"
         },
      "text": "YourEmail@Company.com"
    },
    {
      "type": "setElementText",
      "locator": {
        "type": "css selector",
        "value": "#inputPassword"
      },
      "text": "MyGreatPassword"
    },
    {
      "type": "clickElement",
      "locator": {
        "type": "id",
        "value": "login-btn"
      }
    }
  ],
  "data": {
    "configs": {},
    "source": "none"
  },
  "inputs": [],
  "timeoutSeconds": 60
}

Note: Only the "steps" should be edited for your desired script

Using the Selenium script in a screenshot

Launch the test center and go to the Screenshots page. Enter a URL for the screenshot test so you can remember what page this screenshot is for. The system will rely on the selenium script to go to the proper page, so this URL is not used in making the screenshot. Click on the Advanced Options area, and add the selenium script. We recommend running only one screenshot when first testing a new selenium script – once you have tested it you can rerun the screenshot test and select the browsers you need.

It is suggested to do the following to have the best success rate in creating screenshots using this technique:

  • Keep it simple.

  • Keep the number of actions to a minimum.

  • Have good ids on elements you will be interacting with to keep the selectors simpler.

A more comprehensive list of commands can be found here. Of those commands, the verify, assert, store, print, and close commands are currently unsupported for Screenshot testing.

If you have any questions or concerns, please feel free to reach out to our support team.

See Also

Visual Testing

Highlight search results