Throw error if element found and add exeption if elements not found

How to throw error if particular element is located and add exception if elements are not located

Hi @Bharath.Rajendran - If an element is not found then the script will timeout and the synthetic will fail. To locate an element and fail the script you can look for the element and then throw an exception if that call succeeds.

1 Like

@Bharath.Rajendran - Did Stefan’s comment help you out?

I have similar issue. Our page has marketing popups sometime. I want my script to check for the popup element. If it is there then close it. Else move to the next step. Plaese help.

Hi @sarmistha.pal there a number of options listed in the post below that you could try :slight_smile:


The solution mentioned $browser.isElementPresent, but I don’t see this option is present in NR synthetic script.

Hey @sarmistha.pal - I see that Ruairi’s suggestion is an example from a long time ago, the concept is still absolutely valid and will work for the most part, however, in a Synthetics runtime update since then, a newer version of WebDriverJS was introduced which removed the isElementPresent function from the feature set.

Following that change, you have to create your own elementIsPresent function, which is described with a working example here:

Define the elementIsPresent function somewhere in your script and when you call it, it should return true/false

1 Like

Here is an example function.

async function IsElementPresent(driverBy) {
    var found = await $browser.findElements(driverBy)
    return found.length > 0;

Example usage:
await IsElementPresent($"element_id"));


Sweet!! Thanks for sharing that Stefan :smiley:

Thanks @RyanVeitch, @stefan_garnham. I am trying to use this example. I called the IsElementPresent function in the following way:

console.log('ElementPresentFlag: ’ + IsElementPresent(By.xpath(…)));

For any element (weather it is present in the page or not) I always get the msg:
ElementPresentFlag: [object Promise]

How can I call the function properly to get valid output and based on the element present I can click on it. If is it not present then I want to move to the next step.

The function returns the promise object for chaining. You will need something like:

  var isPresent = await IsElementPresent(By.xpath(...));
  console.log('ElementPresentFlag:' + isPresent);
1 Like

@sarmistha.pal Did Stefan’s suggestion help out?

1 Like