Home > Mobile >  How to get browser console error messages using Selenium WebDriver NodeJS?
How to get browser console error messages using Selenium WebDriver NodeJS?

Time:12-19

In Selenium Webdriver for Javascript/NodeJS, how can I get the console.log and console.error of the browser?

I am using headless browser engines

const { Builder, By, until } = require('selenium-webdriver')
const chrome = require('selenium-webdriver/chrome')
const firefox = require('selenium-webdriver/firefox')

// get selectedBrowser and url from CLI options
let selectedBrowser, url

(async ()=> {
  let driver
  const screen = { width: 1920, height: 1080 }
  switch (selectedBrowser) {
    case 'firefox':
      driver = await new Builder()
        .forBrowser('firefox')
        .setFirefoxOptions(new firefox.Options().headless().windowSize(screen))
        .build()
      break
    case 'chrome':
      driver = await new Builder()
        .forBrowser('chrome')
        .setChromeOptions(new chrome.Options().headless().windowSize(screen))
        .build()
      break
    default:
      throw Error('Wrong browser: '   frontendTest)
  }

  await driver.get(url)

  // etc.
})()

CodePudding user response:

As explained in the official selenium documentation, you must:

first, set the logging preferences

var prefs = new logging.Preferences();
prefs.setLevel(logging.Type.BROWSER, logging.Level.DEBUG);

var caps = Capabilities.chrome();
caps.setLoggingPrefs(prefs);

and then retrieve the logs

driver.manage().logs().get(logging.Type.BROWSER)
     .then(function(entries) {
        entries.forEach(function(entry) {
          console.log('[%s] %s', entry.level.name, entry.message);
        });
     });
  • Related