Skip to main content
Transform your testing process with: Real Device Features, Company-wide Licences, & Test Observability
No Result Found

Log contextual information using console annotations

Use console annotators to customize logs that you want to send to BrowserStack from within the test script for debugging or tracking.

In this guide, you will learn:

Your test script contains contextual information related to the test, such as description of the test, start and end of scenarios, or any other data that you may want to print on the console for debugging and tracking. Using console annotations, you can add configurations in your tests that will log this information on BrowserStack. These logs are available on the Automate Dashboard along with the Selenium raw logs. These logs provide a way for you to quickly search and go to a specific section of the test and troubleshoot any failed tests.

After you run a test that includes console annotations, you can view the logs with these annotations on the Automate Dashboard as seen in the following example:

Console Annotation

Send logs to BrowserStack using JavascriptExecutor

You can send annotations to BrowserStack from within the test script using the the annotate action implemented through the JavascriptExecutor as shown in the following snippets:

JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("browserstack_executor: {\"action\": \"annotate\", \"arguments\": {\"data\": \"<any string>\", \"level\": \"<info/warn/debug/error>\"}}");
driver.executeScript('browserstack_executor: {"action": "annotate", "arguments": {"data":"<any string>","level": "<info/warn/debug/error>"}}');
((IJavaScriptExecutor)driver).ExecuteScript("browserstack_executor: {\"action\": \"annotate\", \"arguments\": {\"data\":\"<any string>\", \"level\": \" <info/warn/debug/error> \"}}");
$web_driver->executeScript('browserstack_executor: {"action": "annotate", "arguments": {"data":"<any string>", "level": "<info/warn/debug/error>"}}' );
driver.execute_script('browserstack_executor: {"action": "annotate", "arguments": {"data":"<any string>", "level": "<info/warn/debug/error>"}}')
caps["javascriptEnabled"] = "true" #Additionally, include this capability for JavaScript Executors to work

driver.execute_script('browserstack_executor: {"action": "annotate", "arguments": {"data":"<any string>", "level": "<info/warn/debug/error>"}}')

The arguments passed in the JavaScript method for setting the status and the corresponding reason for the test are data and level.

  • data accepts a value in string data-type.
  • level accepts the standard log severity levels, namely info , debug , warn, and error . This argument is optional with the default value of info.

Searching and Filtering

After your test script has sent console annotations to BrowserStack, you can find all the annotations pushed to the logs in the Text Logs tab on the Automate dashboard.

You can either search with the logged text in the searchbar or directly navigate to the section of test execution where you want to troubleshoot. This search feature is particularly helpful when your test sessions run for a long duration.

Console Annotation searching

You can also filter these annotated logs based on the severity levels and customize the selection based on your logging patterns.

Console Annotation filtering

Sample code

The following code snippets show the annotation that is sent to BrowserStack when a product is added to the cart.

// Sample test in Java to run Automate session.
import org.openqa.selenium.By;
import org.openqa.selenium.Platform;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.JavascriptExecutor;
import java.net.URL;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class JavaSample {
    public static final String AUTOMATE_USERNAME = "YOUR_USERNAME";
    public static final String AUTOMATE_ACCESS_KEY = "YOUR_ACCESS_KEY";
    public static final String URL = "https://" + AUTOMATE_USERNAME + ":" + AUTOMATE_ACCESS_KEY + "hub.browserstack.com/wd/hub";
    public static void main(String[] args) throws Exception {
        DesiredCapabilities capabilities = new DesiredCapabilities();
        HashMap<String, Object> browserstackOptions = new HashMap<String, Object>();
        browserstackOptions.put("osVersion", "14");
        browserstackOptions.put("deviceName", "iPhone 12");
        browserstackOptions.put("realMobile", "true");
        browserstackOptions.put("projectName", "BStack Sample Test");
        browserstackOptions.put("buildName", "BStack Build Number 1");
        capabilities.setCapability("bstack:options", browserstackOptions);


        final WebDriver driver = new RemoteWebDriver(new URL(URL), caps);
        try {
            // logging start of test session at BrowserStack
            annotate("Add to cart","info",driver);
            driver.get("https://bstackdemo.com/");
            final WebDriverWait wait = new WebDriverWait(driver, 10);
            wait.until(ExpectedConditions.titleIs("StackDemo"));
            // getting name of the product
            String product_name = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id=\'1\']/p"))).getText();
            // waiting for the Add to cart button to be clickable
            WebElement cart_btn = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@id=\'1\']/div[4]")));
            // clicking the 'Add to cart' button
            cart_btn.click();
            // checking if the Cart pane is visible
            wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("float-cart__content")));
            // getting the product's name added in the cart
            final String product_in_cart = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id=\'__next\']/div/div/div[2]/div[2]/div[2]/div/div[3]/p[1]"))).getText();
            // logging variable for debugging purpose
            annotate("product in cart = " + product_in_cart,"debug",driver);
            // verifying whether the product added to cart is available in the cart
            if (product_name.equals(product_in_cart)) {
                markTestStatus("passed", "Product has been successfully added to the cart!", driver);
            }else{
                markTestStatus("failed", "Product has not successfully added to the cart!", driver);
                annotate("Product not found in cart. Test Failed" ,"error",driver);
            }
        } catch (Exception e) {
            markTestStatus("failed", "Some elements failed to load", driver);
        }
        driver.quit();
    }
    // This method accepts the status, reason and WebDriver instance and marks the test on BrowserStack
    public static void markTestStatus(String status, String reason, WebDriver driver) {
        final JavascriptExecutor jse = (JavascriptExecutor) driver;
        jse.executeScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\": \""+ status + "\", \"reason\": \"" + reason + "\"}}");
    }

    public static void annotate(String data, String level, WebDriver driver) {
        final JavascriptExecutor jse = (JavascriptExecutor) driver;
        jse.executeScript("browserstack_executor: {\"action\": \"annotate\", \"arguments\": {\"data\": \""+ data + "\", \"level\": \"" + level + "\"}}");
    }
} 
var webdriver = require('selenium-webdriver');
const { By } = require('selenium-webdriver');
const assert = require('assert');

// Input capabilities
var capabilities = {
	'bstack:options' : {
		"osVersion" : "14",
		"deviceName" : "iPhone 12",
		"realMobile" : "true",
		"projectName" : "BStack Sample Test",
		"buildName" : "BStack Build Number 1",
		"userName" : "YOUR_USERNAME",
		"accessKey" : "YOUR_ACCESS_KEY",
	},
	"browserName" : "safari",
}

function sleep (time) {
    return new Promise((resolve) => setTimeout(resolve, time));
  }



async function runTestWithCaps () {
    let driver = new webdriver.Builder().usingServer(`https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub.browserstack.com/wd/hub`).withCapabilities(capabilities).build();
    try{
      await  driver.executeScript('browserstack_executor: {"action": "annotate", "arguments": {"data":"Scenario : Add to cart","level": "info"}}');
      await driver.get("https://bstackdemo.com/");
      await driver.wait(webdriver.until.titleMatches(/StackDemo/i), 10000);
      // locating product on webpage
      const productOnScreen = await driver.wait(webdriver.until.elementLocated(By.xpath('//*[@id="1"]/p')), 10000)
      // getting name of the product when the product is visible
      const productText =  await driver.wait(webdriver.until.elementIsVisible(productOnScreen, 10000)).getText();
      // clicking the 'Add to cart' button
      await driver.wait(webdriver.until.elementIsVisible(driver.findElement(By.xpath('//*[@id="1"]/div[4]'), 10000))).click();
      // waiting until the Cart pane has been displayed on the webpage
      await driver.wait(webdriver.until.elementIsVisible(driver.findElement(By.className('float-cart__content'), 10000)));
      // locating product in cart
      
      const productInCart = await driver.wait(webdriver.until.elementLocated(By.xpath('//*[@id="__next"]/div/div/div[2]/div[2]/div[2]/div/div[3]/p[1]')), 10000);
      // getting name of the product in cart if the product is visible on web page
      const productCartText =  await driver.wait(webdriver.until.elementIsVisible(productInCart, 10000)).getText();
      

      await driver.executeScript('browserstack_executor: {"action": "annotate", "arguments": {"data":"product in cart = '+ productCartText + '","level": "debug"}}');
      // checking whether product has been added to cart by comparing product name
      assert(productText === productCartText);
      //marking the test as Passed if product has been added to the cart
      await driver.executeScript(
        'browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"passed","reason": "Product has been successfully added to the cart!"}}'
      );
      await  driver.executeScript('browserstack_executor: {"action": "annotate", "arguments": {"data":"Scenario : Add to cart completes","level": "info"}}');
    } catch(e) {
      //marking the test as Failed if product has not been added to the cart
      console.log("Error:", e.message)
      await driver.executeScript(
        'browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"failed","reason": "Add to cart failed"}}'
      );
      await  driver.executeScript('browserstack_executor: {"action": "annotate", "arguments": {"data":"Scenario : Add to cart - failed","level": "error"}}');
    
    }
    await driver.quit();
  }
  runTestWithCaps();

using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Remote;
using OpenQA.Selenium.Support.UI;
namespace SeleniumTest {
  class Program {
    static void Main(string[] args) {
      IWebDriver driver;
      SafariOptions capabilities = new SafariOptions();
      Dictionary<string, object> browserstackOptions = new Dictionary<string, object>();
      browserstackOptions.Add("osVersion", "14");
      browserstackOptions.Add("deviceName", "iPhone 12");
      browserstackOptions.Add("realMobile", "true");
      browserstackOptions.Add("projectName", "BStack Sample Test");
      browserstackOptions.Add("buildName", "BStack Build Number 1");
      browserstackOptions.Add("local", "true");
      browserstackOptions.Add("userName", "YOUR_USERNAME");
      browserstackOptions.Add("accessKey", "YOUR_ACCESSS_KEY");
      capabilities.AddAdditionalOption("bstack:options", browserstackOptions);

      driver = new RemoteWebDriver(new Uri("https://hub.browserstack.com/wd/hub/"), capability);
      WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
      try
      {
        // logging start of test session at BrowserStack
        ((IJavaScriptExecutor)driver).ExecuteScript("browserstack_executor: {\"action\": \"annotate\", \"arguments\": {\"data\":\"Add to cart\", \"level\": \"info\"}}");
        
        driver.Navigate().GoToUrl("https://bstackdemo.com/");
        // getting name of the product
        IWebElement product = driver.FindElement(By.XPath("//*[@id='1']/p"));
        wait.Until(driver => product.Displayed);
        String product_on_page = product.Text;
        // clicking the 'Add to Cart' button
        IWebElement cart_btn = driver.FindElement(By.XPath("//*[@id='1']/div[4]"));
        wait.Until(driver => cart_btn.Displayed);
        cart_btn.Click();
        // waiting for the Cart pane to appear
        wait.Until(driver => driver.FindElement(By.ClassName("float-cart__content")).Displayed);
        // getting name of the product in the cart
        String product_in_cart = driver.FindElement(By.XPath("//*[@id='__next']/div/div/div[2]/div[2]/div[2]/div/div[3]/p[1]")).Text;
        // logging variable for debugging purpose
        ((IJavaScriptExecutor)driver).ExecuteScript("browserstack_executor: {\"action\": \"annotate\", \"arguments\": {\"data\":\"product in cart = "+ product_in_cart + "\", \"level\": \"debug\"}}");

        if (product_on_page == product_in_cart)
        {
            ((IJavaScriptExecutor)driver).ExecuteScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\":\"passed\", \"reason\": \" Product has been successfully added to the cart!\"}}");
        }
      }
      catch {
        ((IJavaScriptExecutor) driver).ExecuteScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\":\"failed\", \"reason\": \" Some elements failed to load.\"}}");
      }
      driver.Quit();
    }
  }
}
<?php
require_once('vendor/autoload.php');
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Facebook\WebDriver\WebDriverBy;
use Facebook\WebDriver\WebDriverExpectedCondition;
$caps = array(
	'bstack:options' => array(
		"osVersion" => "14",
		"deviceName" => "iPhone 12",
		"realMobile" => "true",
		"projectName" => "BStack Sample Test",
		"buildName" => "BStack Build Number 1",
	),
)
$web_driver = RemoteWebDriver::create("https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub.browserstack.com/wd/hub",$caps);
try{
    # logging start of test session at BrowserStack
    $web_driver->executeScript('browserstack_executor: {"action": "annotate", "arguments": {"data":"Scenario : Add to cart","level": "info"}}' );
    $web_driver->get("https://bstackdemo.com/");
    $web_driver->wait(10000)->until(WebDriverExpectedCondition::titleIs("StackDemo"));
    # getting text of the product
    $product_on_page = $web_driver->wait(10000)->until(WebDriverExpectedCondition::presenceOfElementLocated(WebDriverBy::XPath("//*[@id='1']/p")))->getText();
    # clicking the 'Add to cart' button
    $web_driver->wait(10000)->until(WebDriverExpectedCondition::presenceOfElementLocated(WebDriverBy::XPath("//*[@id='1']/div[4]")))->click();
    # checking whether the cart pane is present on webpage
    $web_driver->wait(10000)->until(WebDriverExpectedCondition::presenceOfElementLocated(WebDriverBy::className("float-cart__content")));
    # getting text of the product
    $product_in_cart = $web_driver->wait(10000)->until(WebDriverExpectedCondition::presenceOfElementLocated(WebDriverBy::XPath("//*[@id='__next']/div/div/div[2]/div[2]/div[2]/div/div[3]/p[1]")))->getText();
    # logging variable for debugging purpose
    $web_driver->executeScript('browserstack_executor: {"action": "annotate", "arguments": {"data":"product in cart = '+ productCartText + '","level": "debug"}}');

    # Setting the status of test as 'passed' or 'failed' based on the condition; if title of the web page starts with 'BrowserStack'
    if ($product_on_page == $product_in_cart){
        $web_driver->executeScript('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"passed", "reason": "Product has been successfully added to the cart!"}}' );
        // logging completion of scenario
        $web_driver->executeScript('browserstack_executor: {"action": "annotate", "arguments": {"data":"Scenario : Add to cart completes","level": "info"}}');

    }  else {
        $web_driver->executeScript('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"failed", "reason": "Failed to add product to the cart or some elements might have failed to load."}}');
    }
}
catch(Exception $e){
    echo 'Message: ' .$e->getMessage();
}
$web_driver->quit();
?> 
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
desired_cap = {
	'bstack:options' : {
		"osVersion" : "14",
		"deviceName" : "iPhone 12",
		"realMobile" : "true",
		"projectName" : "BStack Sample Test",
		"buildName" : "BStack Build Number 1",
	},
}
driver = webdriver.Remote(
    command_executor='https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub.browserstack.com/wd/hub',
    desired_capabilities=desired_cap)
try:
    driver.get("https://bstackdemo.com/")
    # Logging start of test session at BrowserStack
    driver.execute_script('browserstack_executor: {"action": "annotate", "arguments": {"data":"Scenario : Add to cart","level": "info"}}' );

    WebDriverWait(driver, 10).until(EC.title_contains("StackDemo"))
    # Get text of an product - iPhone 12
    item_on_page =  WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.XPATH, '//*[@id="1"]/p'))).text
    # Click the 'Add to cart' button if it is visible
    WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.XPATH, '//*[@id="1"]/div[4]'))).click()
    # Check if the Cart pane is visible
    WebDriverWait(driver,10).until(EC.visibility_of_element_located((By.CLASS_NAME, "float-cart__content")))
    ## Get text of product in cart
    item_in_cart = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.XPATH, '//*[@id="__next"]/div/div/div[2]/div[2]/div[2]/div/div[3]/p[1]'))).text
    # logging variable for debugging purpose
    driver.execute_script('browserstack_executor: {"action": "annotate", "arguments": {"data":"product in cart = '+ productCartText + '","level": "debug"}}');

    # Verify whether the product (iPhone 12) is added to cart
    if item_on_page == item_in_cart:
        # Set the status of test as 'passed' or 'failed' based on the condition; if item is added to cart
        driver.execute_script('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"passed", "reason": "iPhone 12 has been successfully added to the cart!"}}')
        # logging completion of scenario
        driver.execute_script('browserstack_executor: {"action": "annotate", "arguments": {"data":"Scenario : Add to cart completes","level": "info"}}');
except NoSuchElementException:
    driver.execute_script('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"failed", "reason": "Some elements failed to load"}}')
# Stop the driver
driver.quit() 
require 'rubygems'
require 'selenium-webdriver'
# Input capabilities
capabilities = {
	'bstack:options' => {
		"osVersion" => "14",
		"deviceName" => "iPhone 12",
		"realMobile" => "true",
		"projectName" => "BStack Sample Test",
		"buildName" => "BStack Build Number 1",
	},
}
driver = Selenium::WebDriver.for(:remote,
  :url => "https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub.browserstack.com/wd/hub",
  :desired_capabilities => caps)
begin
    # logging start of test session at BrowserStack
    driver.execute_script('browserstack_executor: {"action": "annotate", "arguments": {"data":"Scenario : Add to cart","level": "info"}}' )
    # opening the bstackdemo.com website
    driver.navigate.to "https://bstackdemo.com/"
    wait = Selenium::WebDriver::Wait.new(:timeout => 10) # seconds
    wait.until { !driver.title.match(/StackDemo/i).nil? }
    # getting name of the product available on the webpage
    product = driver.find_element(:xpath, '//*[@id="1"]/p')
    wait.until { product.displayed? }
    product_text = product.text
    # waiting until the Add to Cart button is displayed on webpage and then clicking it
    cart_btn = driver.find_element(:xpath, '//*[@id="1"]/div[4]')
    wait.until { cart_btn.displayed? }
    cart_btn.click
    # waiting until the Cart pane appears
    wait.until { driver.find_element(:xpath, '//*[@id="__next"]/div/div/div[2]/div[2]/div[2]/div/div[3]/p[1]').displayed? }
    # getting name of the product in the cart
    product_in_cart = driver.find_element(:xpath, '//*[@id="__next"]/div/div/div[2]/div[2]/div[2]/div/div[3]/p[1]')
    wait.until { product_in_cart.displayed? }
    product_in_cart_text = product_in_cart.text

    # logging variable for debugging purpose
    driver.execute_script('browserstack_executor: {"action": "annotate", "arguments": {"data":"product in cart = '+ product_in_cart_text + '","level": "debug"}}')

    # checking if the product has been added to the cart
    if product_text.eql? product_in_cart_text
        # marking test as 'passed' if the product is successfully added to the cart
        driver.execute_script('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"passed", "reason": "Product has been successfully added to the cart!"}}')
        # logging completion of scenario
        driver.execute_script('browserstack_executor: {"action": "annotate", "arguments": {"data":"Scenario : Add to cart completes","level": "info"}}')
    else
        # marking test as 'failed' if the product is not added to the cart
        driver.execute_script('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"failed", "reason": "Failed to add product to the cart"}}')
    end
# marking test as 'failed' if test script is unable to open the bstackdemo.com website
rescue
    driver.execute_script('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"failed", "reason": "Some elements failed to load"}}')
end
driver.quit 
// Sample test in Java to run Automate session.
import org.openqa.selenium.By;
import org.openqa.selenium.Platform;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.JavascriptExecutor;
import java.net.URL;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class JavaSample {
    public static final String AUTOMATE_USERNAME = "YOUR_USERNAME";
    public static final String AUTOMATE_ACCESS_KEY = "YOUR_ACCESS_KEY";
    public static final String URL = "https://" + AUTOMATE_USERNAME + ":" + AUTOMATE_ACCESS_KEY + "hub.browserstack.com/wd/hub";
    public static void main(String[] args) throws Exception {
        DesiredCapabilities caps = new DesiredCapabilities();
        caps.setCapability("os_version", "11");
        caps.setCapability("browser", "Chrome");
        caps.setCapability("browser_version", "latest");
        caps.setCapability("os", "Windows");
        caps.setCapability("name", "BStack-[Java] Sample Test"); // test name
        caps.setCapability("build", "BStack Build Number 1"); // CI/CD job or build name
        final WebDriver driver = new RemoteWebDriver(new URL(URL), caps);
        try {
            // logging start of test session at BrowserStack
            annotate("Add to cart","info",driver);
            driver.get("https://bstackdemo.com/");
            final WebDriverWait wait = new WebDriverWait(driver, 10);
            wait.until(ExpectedConditions.titleIs("StackDemo"));
            // getting name of the product
            String product_name = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id=\'1\']/p"))).getText();
            // waiting for the Add to cart button to be clickable
            WebElement cart_btn = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@id=\'1\']/div[4]")));
            // clicking the 'Add to cart' button
            cart_btn.click();
            // checking if the Cart pane is visible
            wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("float-cart__content")));
            // getting the product's name added in the cart
            final String product_in_cart = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id=\'__next\']/div/div/div[2]/div[2]/div[2]/div/div[3]/p[1]"))).getText();
            // logging variable for debugging purpose
            annotate("product in cart = " + product_in_cart,"debug",driver);
            // verifying whether the product added to cart is available in the cart
            if (product_name.equals(product_in_cart)) {
                markTestStatus("passed", "Product has been successfully added to the cart!", driver);
            }else{
                markTestStatus("failed", "Product has not successfully added to the cart!", driver);
                annotate("Product not found in cart. Test Failed" ,"error",driver);
            }
        } catch (Exception e) {
            markTestStatus("failed", "Some elements failed to load", driver);
        }
        driver.quit();
    }
    // This method accepts the status, reason and WebDriver instance and marks the test on BrowserStack
    public static void markTestStatus(String status, String reason, WebDriver driver) {
        final JavascriptExecutor jse = (JavascriptExecutor) driver;
        jse.executeScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\": \""+ status + "\", \"reason\": \"" + reason + "\"}}");
    }

    public static void annotate(String data, String level, WebDriver driver) {
        final JavascriptExecutor jse = (JavascriptExecutor) driver;
        jse.executeScript("browserstack_executor: {\"action\": \"annotate\", \"arguments\": {\"data\": \""+ data + "\", \"level\": \"" + level + "\"}}");
    }
} 
var webdriver = require('selenium-webdriver');
const { By } = require('selenium-webdriver');
const assert = require('assert');

// Input capabilities
var capabilities = {
  'browserName': 'chrome',
  'browserVersion': '72.0',
  'os': '',
  
}
function sleep (time) {
    return new Promise((resolve) => setTimeout(resolve, time));
  }



async function runTestWithCaps () {
    let driver = new webdriver.Builder().usingServer(`https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub.browserstack.com/wd/hub`).withCapabilities(capabilities).build();
    try{
      await  driver.executeScript('browserstack_executor: {"action": "annotate", "arguments": {"data":"Scenario : Add to cart","level": "info"}}');
      await driver.get("https://bstackdemo.com/");
      await driver.wait(webdriver.until.titleMatches(/StackDemo/i), 10000);
      // locating product on webpage
      const productOnScreen = await driver.wait(webdriver.until.elementLocated(By.xpath('//*[@id="1"]/p')), 10000)
      // getting name of the product when the product is visible
      const productText =  await driver.wait(webdriver.until.elementIsVisible(productOnScreen, 10000)).getText();
      // clicking the 'Add to cart' button
      await driver.wait(webdriver.until.elementIsVisible(driver.findElement(By.xpath('//*[@id="1"]/div[4]'), 10000))).click();
      // waiting until the Cart pane has been displayed on the webpage
      await driver.wait(webdriver.until.elementIsVisible(driver.findElement(By.className('float-cart__content'), 10000)));
      // locating product in cart
      
      const productInCart = await driver.wait(webdriver.until.elementLocated(By.xpath('//*[@id="__next"]/div/div/div[2]/div[2]/div[2]/div/div[3]/p[1]')), 10000);
      // getting name of the product in cart if the product is visible on web page
      const productCartText =  await driver.wait(webdriver.until.elementIsVisible(productInCart, 10000)).getText();
      

      await driver.executeScript('browserstack_executor: {"action": "annotate", "arguments": {"data":"product in cart = '+ productCartText + '","level": "debug"}}');
      // checking whether product has been added to cart by comparing product name
      assert(productText === productCartText);
      //marking the test as Passed if product has been added to the cart
      await driver.executeScript(
        'browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"passed","reason": "Product has been successfully added to the cart!"}}'
      );
      await  driver.executeScript('browserstack_executor: {"action": "annotate", "arguments": {"data":"Scenario : Add to cart completes","level": "info"}}');
    } catch(e) {
      //marking the test as Failed if product has not been added to the cart
      console.log("Error:", e.message)
      await driver.executeScript(
        'browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"failed","reason": "Add to cart failed"}}'
      );
      await  driver.executeScript('browserstack_executor: {"action": "annotate", "arguments": {"data":"Scenario : Add to cart - failed","level": "error"}}');
    
    }
    await driver.quit();
  }
  runTestWithCaps();

using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Remote;
using OpenQA.Selenium.Support.UI;
namespace SeleniumTest {
  class Program {
    static void Main(string[] args) {
      IWebDriver driver;
      OpenQA.Selenium.Safari.SafariOptions capability = new OpenQA.Selenium.Safari.SafariOptions();
      capability.AddAdditionalCapability("browser", "iPhone");
      capability.AddAdditionalCapability("device", "iPhone 11");
      capability.AddAdditionalCapability("realMobile", "true");
      capability.AddAdditionalCapability("os_version", "14.0");
      capability.AddAdditionalCapability("name", "BStack-[C_sharp] Sample Test"); // test name
      capability.AddAdditionalCapability("build", "BStack Build Number 1"); // CI/CD job or build name
      capability.AddAdditionalCapability("browserstack.user", "YOUR_USERNAME");
      capability.AddAdditionalCapability("browserstack.key", "YOUR_ACCESS_KEY");
      driver = new RemoteWebDriver(new Uri("https://hub.browserstack.com/wd/hub/"), capability);
      WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
      try
      {
        // logging start of test session at BrowserStack
        ((IJavaScriptExecutor)driver).ExecuteScript("browserstack_executor: {\"action\": \"annotate\", \"arguments\": {\"data\":\"Add to cart\", \"level\": \"info\"}}");
        
        driver.Navigate().GoToUrl("https://bstackdemo.com/");
        // getting name of the product
        IWebElement product = driver.FindElement(By.XPath("//*[@id='1']/p"));
        wait.Until(driver => product.Displayed);
        String product_on_page = product.Text;
        // clicking the 'Add to Cart' button
        IWebElement cart_btn = driver.FindElement(By.XPath("//*[@id='1']/div[4]"));
        wait.Until(driver => cart_btn.Displayed);
        cart_btn.Click();
        // waiting for the Cart pane to appear
        wait.Until(driver => driver.FindElement(By.ClassName("float-cart__content")).Displayed);
        // getting name of the product in the cart
        String product_in_cart = driver.FindElement(By.XPath("//*[@id='__next']/div/div/div[2]/div[2]/div[2]/div/div[3]/p[1]")).Text;
        // logging variable for debugging purpose
        ((IJavaScriptExecutor)driver).ExecuteScript("browserstack_executor: {\"action\": \"annotate\", \"arguments\": {\"data\":\"product in cart = "+ product_in_cart + "\", \"level\": \"debug\"}}");

        if (product_on_page == product_in_cart)
        {
            ((IJavaScriptExecutor)driver).ExecuteScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\":\"passed\", \"reason\": \" Product has been successfully added to the cart!\"}}");
        }
      }
      catch {
        ((IJavaScriptExecutor) driver).ExecuteScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\":\"failed\", \"reason\": \" Some elements failed to load.\"}}");
      }
      driver.Quit();
    }
  }
}
<?php
require_once('vendor/autoload.php');
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Facebook\WebDriver\WebDriverBy;
use Facebook\WebDriver\WebDriverExpectedCondition;
$caps = array(
    "browserName" => "iPhone",
    "device" => "iPhone 11",
    "realMobile" => "true",
    "os_version" => "14.0",
    "name" => "BStack-[Php] Sample Test", // test name
    "build" => "BStack Build Number 1" // CI/CD job or build name
);
$web_driver = RemoteWebDriver::create("https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub.browserstack.com/wd/hub",$caps);
try{
    # logging start of test session at BrowserStack
    $web_driver->executeScript('browserstack_executor: {"action": "annotate", "arguments": {"data":"Scenario : Add to cart","level": "info"}}' );
    $web_driver->get("https://bstackdemo.com/");
    $web_driver->wait(10000)->until(WebDriverExpectedCondition::titleIs("StackDemo"));
    # getting text of the product
    $product_on_page = $web_driver->wait(10000)->until(WebDriverExpectedCondition::presenceOfElementLocated(WebDriverBy::XPath("//*[@id='1']/p")))->getText();
    # clicking the 'Add to cart' button
    $web_driver->wait(10000)->until(WebDriverExpectedCondition::presenceOfElementLocated(WebDriverBy::XPath("//*[@id='1']/div[4]")))->click();
    # checking whether the cart pane is present on webpage
    $web_driver->wait(10000)->until(WebDriverExpectedCondition::presenceOfElementLocated(WebDriverBy::className("float-cart__content")));
    # getting text of the product
    $product_in_cart = $web_driver->wait(10000)->until(WebDriverExpectedCondition::presenceOfElementLocated(WebDriverBy::XPath("//*[@id='__next']/div/div/div[2]/div[2]/div[2]/div/div[3]/p[1]")))->getText();
    # logging variable for debugging purpose
    $web_driver->executeScript('browserstack_executor: {"action": "annotate", "arguments": {"data":"product in cart = '+ productCartText + '","level": "debug"}}');

    # Setting the status of test as 'passed' or 'failed' based on the condition; if title of the web page starts with 'BrowserStack'
    if ($product_on_page == $product_in_cart){
        $web_driver->executeScript('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"passed", "reason": "Product has been successfully added to the cart!"}}' );
        // logging completion of scenario
        $web_driver->executeScript('browserstack_executor: {"action": "annotate", "arguments": {"data":"Scenario : Add to cart completes","level": "info"}}');

    }  else {
        $web_driver->executeScript('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"failed", "reason": "Failed to add product to the cart or some elements might have failed to load."}}');
    }
}
catch(Exception $e){
    echo 'Message: ' .$e->getMessage();
}
$web_driver->quit();
?> 
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
desired_cap = {
 'browserName': 'iPhone',
 'device': 'iPhone 11',
 'realMobile': 'true',
 'os_version': '14.0',
 'name': 'BStack-[Python] Sample Test', # test name
 'build': 'BStack Build Number 1' # CI/CD job or build name
}
driver = webdriver.Remote(
    command_executor='https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub.browserstack.com/wd/hub',
    desired_capabilities=desired_cap)
try:
    driver.get("https://bstackdemo.com/")
    # Logging start of test session at BrowserStack
    driver.execute_script('browserstack_executor: {"action": "annotate", "arguments": {"data":"Scenario : Add to cart","level": "info"}}' );

    WebDriverWait(driver, 10).until(EC.title_contains("StackDemo"))
    # Get text of an product - iPhone 12
    item_on_page =  WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.XPATH, '//*[@id="1"]/p'))).text
    # Click the 'Add to cart' button if it is visible
    WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.XPATH, '//*[@id="1"]/div[4]'))).click()
    # Check if the Cart pane is visible
    WebDriverWait(driver,10).until(EC.visibility_of_element_located((By.CLASS_NAME, "float-cart__content")))
    ## Get text of product in cart
    item_in_cart = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.XPATH, '//*[@id="__next"]/div/div/div[2]/div[2]/div[2]/div/div[3]/p[1]'))).text
    # logging variable for debugging purpose
    driver.execute_script('browserstack_executor: {"action": "annotate", "arguments": {"data":"product in cart = '+ productCartText + '","level": "debug"}}');

    # Verify whether the product (iPhone 12) is added to cart
    if item_on_page == item_in_cart:
        # Set the status of test as 'passed' or 'failed' based on the condition; if item is added to cart
        driver.execute_script('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"passed", "reason": "iPhone 12 has been successfully added to the cart!"}}')
        # logging completion of scenario
        driver.execute_script('browserstack_executor: {"action": "annotate", "arguments": {"data":"Scenario : Add to cart completes","level": "info"}}');
except NoSuchElementException:
    driver.execute_script('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"failed", "reason": "Some elements failed to load"}}')
# Stop the driver
driver.quit() 
require 'rubygems'
require 'selenium-webdriver'
# Input capabilities
caps = Selenium::WebDriver::Remote::Capabilities.new
caps['device'] = 'iPhone 11'
caps['realMobile'] = 'true'
caps['os_version'] = '14.0'
caps['javascriptEnabled'] = 'true'
caps['name'] = 'BStack-[Ruby] Sample Test' # test name
caps['build'] = 'BStack Build Number 1' # CI/CD job or build name
driver = Selenium::WebDriver.for(:remote,
  :url => "https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub.browserstack.com/wd/hub",
  :desired_capabilities => caps)
begin
    # logging start of test session at BrowserStack
    driver.execute_script('browserstack_executor: {"action": "annotate", "arguments": {"data":"Scenario : Add to cart","level": "info"}}' )
    # opening the bstackdemo.com website
    driver.navigate.to "https://bstackdemo.com/"
    wait = Selenium::WebDriver::Wait.new(:timeout => 10) # seconds
    wait.until { !driver.title.match(/StackDemo/i).nil? }
    # getting name of the product available on the webpage
    product = driver.find_element(:xpath, '//*[@id="1"]/p')
    wait.until { product.displayed? }
    product_text = product.text
    # waiting until the Add to Cart button is displayed on webpage and then clicking it
    cart_btn = driver.find_element(:xpath, '//*[@id="1"]/div[4]')
    wait.until { cart_btn.displayed? }
    cart_btn.click
    # waiting until the Cart pane appears
    wait.until { driver.find_element(:xpath, '//*[@id="__next"]/div/div/div[2]/div[2]/div[2]/div/div[3]/p[1]').displayed? }
    # getting name of the product in the cart
    product_in_cart = driver.find_element(:xpath, '//*[@id="__next"]/div/div/div[2]/div[2]/div[2]/div/div[3]/p[1]')
    wait.until { product_in_cart.displayed? }
    product_in_cart_text = product_in_cart.text

    # logging variable for debugging purpose
    driver.execute_script('browserstack_executor: {"action": "annotate", "arguments": {"data":"product in cart = '+ product_in_cart_text + '","level": "debug"}}')

    # checking if the product has been added to the cart
    if product_text.eql? product_in_cart_text
        # marking test as 'passed' if the product is successfully added to the cart
        driver.execute_script('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"passed", "reason": "Product has been successfully added to the cart!"}}')
        # logging completion of scenario
        driver.execute_script('browserstack_executor: {"action": "annotate", "arguments": {"data":"Scenario : Add to cart completes","level": "info"}}')
    else
        # marking test as 'failed' if the product is not added to the cart
        driver.execute_script('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"failed", "reason": "Failed to add product to the cart"}}')
    end
# marking test as 'failed' if test script is unable to open the bstackdemo.com website
rescue
    driver.execute_script('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"failed", "reason": "Some elements failed to load"}}')
end
driver.quit 

Check this page for a list of various JavaScript Executors that BrowserStack offers.

We're sorry to hear that. Please share your feedback so we can do better

Contact our Support team for immediate help while we work on improving our docs.

We're continuously improving our docs. We'd love to know what you liked





Thank you for your valuable feedback

Is this page helping you?

Yes
No

We're sorry to hear that. Please share your feedback so we can do better

Contact our Support team for immediate help while we work on improving our docs.

We're continuously improving our docs. We'd love to know what you liked





Thank you for your valuable feedback!

Talk to an Expert
Download Copy Check Circle