CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-wd

WebDriver/Selenium 2 Node.js client for browser automation and testing

Pending
Overview
Eval results
Files

javascript-execution.mddocs/

JavaScript Execution

Execute JavaScript code in the browser context with safe evaluation, error handling, and support for both synchronous and asynchronous execution.

Capabilities

Basic JavaScript Execution

Execute JavaScript code and retrieve results from the browser context.

/**
 * Execute JavaScript code in browser
 * @param code - JavaScript code as string or function
 * @param args - Arguments to pass to the script (optional)
 * @param cb - Callback receiving (err, result)
 */
execute(code: string | function, args?: any[], cb?: callback): any;

/**
 * Execute JavaScript with safe error handling
 * @param code - JavaScript code as string or function
 * @param args - Arguments to pass to the script (optional)
 * @param cb - Callback receiving (err, result)
 */
safeExecute(code: string | function, args?: any[], cb?: callback): any;

Usage Examples:

// Execute simple JavaScript
browser.execute('return document.title;', function(err, title) {
  console.log('Page title:', title);
});

// Execute with arguments
browser.execute(
  'return arguments[0] + arguments[1];',
  [5, 10],
  function(err, result) {
    console.log('5 + 10 =', result); // 15
  }
);

// Execute function (will be serialized)
browser.execute(function() {
  return {
    url: window.location.href,
    userAgent: navigator.userAgent,
    cookieCount: document.cookies.length
  };
}, function(err, info) {
  console.log('Browser info:', info);
});

// Safe execution handles errors gracefully
browser.safeExecute('return nonExistentVariable.property;', function(err, result) {
  if (err) {
    console.log('Script error handled safely');
  } else {
    console.log('Result:', result);
  }
});

JavaScript Evaluation

Evaluate JavaScript expressions and return values.

/**
 * Evaluate JavaScript expression and return result
 * @param code - JavaScript expression to evaluate
 * @param cb - Callback receiving (err, value)
 */
eval(code: string, cb?: callback): any;

/**
 * Safely evaluate JavaScript expression
 * @param code - JavaScript expression to evaluate
 * @param cb - Callback receiving (err, value)
 */
safeEval(code: string, cb?: callback): any;

Usage Examples:

// Evaluate expressions
browser.eval('document.querySelectorAll("a").length', function(err, linkCount) {
  console.log('Number of links on page:', linkCount);
});

browser.eval('window.innerWidth', function(err, width) {
  console.log('Browser width:', width);
});

// Safe evaluation
browser.safeEval('someUndefinedVariable', function(err, result) {
  if (err) {
    console.log('Variable not defined, using default');
    result = 'default_value';
  }
  console.log('Result:', result);
});

// Promise chain evaluation
browser
  .get('https://example.com')
  .eval('document.readyState')
  .then(state => {
    console.log('Document ready state:', state);
    if (state === 'complete') {
      return browser.eval('document.querySelectorAll("img").length');
    }
  })
  .then(imageCount => {
    console.log('Images on page:', imageCount);
  });

Asynchronous JavaScript Execution

Execute JavaScript that requires async operations like AJAX calls or timers.

/**
 * Execute asynchronous JavaScript code
 * @param code - Async JavaScript code as string or function
 * @param args - Arguments to pass to the script (optional)
 * @param cb - Callback receiving (err, result)
 */
executeAsync(code: string | function, args?: any[], cb?: callback): any;

/**
 * Safely execute asynchronous JavaScript
 * @param code - Async JavaScript code as string or function
 * @param args - Arguments to pass to the script (optional)
 * @param cb - Callback receiving (err, result)
 */
safeExecuteAsync(code: string | function, args?: any[], cb?: callback): any;

Usage Examples:

// Execute async JavaScript with callback
browser.executeAsync(function() {
  var callback = arguments[arguments.length - 1];
  
  setTimeout(function() {
    callback('Delayed result after 2 seconds');
  }, 2000);
}, function(err, result) {
  console.log('Async result:', result);
});

// AJAX call in browser
browser.executeAsync(function() {
  var callback = arguments[arguments.length - 1];
  
  fetch('/api/data')
    .then(response => response.json())
    .then(data => callback(data))
    .catch(error => callback({error: error.message}));
}, function(err, data) {
  console.log('API response:', data);
});

// Async with arguments
browser.executeAsync(
  function(url) {
    var callback = arguments[arguments.length - 1];
    
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url);
    xhr.onload = function() {
      callback({
        status: xhr.status,
        response: xhr.responseText
      });
    };
    xhr.send();
  },
  ['/api/status'],
  function(err, response) {
    console.log('XHR response:', response);
  }
);

DOM Manipulation

Common DOM operations through JavaScript execution.

Usage Examples:

// Modify DOM elements
browser.execute(function() {
  document.getElementById('message').innerHTML = 'Hello from WebDriver!';
  document.getElementById('message').style.color = 'red';
});

// Trigger events
browser.execute(function() {
  var button = document.getElementById('hidden-button');
  var event = new MouseEvent('click', {
    bubbles: true,
    cancelable: true
  });
  button.dispatchEvent(event);
});

// Scroll to element
browser.execute(function() {
  var element = document.querySelector('.target-section');
  element.scrollIntoView({behavior: 'smooth'});
});

// Get computed styles
browser.execute(function() {
  var element = document.getElementById('styled-element');
  var styles = window.getComputedStyle(element);
  return {
    color: styles.color,
    fontSize: styles.fontSize,
    display: styles.display
  };
}, function(err, styles) {
  console.log('Element styles:', styles);
});

Browser API Access

Access browser APIs and properties through JavaScript execution.

Usage Examples:

// Get browser information
browser.execute(function() {
  return {
    userAgent: navigator.userAgent,
    language: navigator.language,
    platform: navigator.platform,
    cookieEnabled: navigator.cookieEnabled,
    onLine: navigator.onLine
  };
}, function(err, browserInfo) {
  console.log('Browser info:', browserInfo);
});

// Access localStorage
browser.execute(function() {
  localStorage.setItem('testKey', 'testValue');
  return localStorage.getItem('testKey');
}, function(err, value) {
  console.log('LocalStorage value:', value);
});

// Get page performance data
browser.execute(function() {
  var perf = performance.timing;
  return {
    domContentLoaded: perf.domContentLoadedEventEnd - perf.navigationStart,
    pageLoad: perf.loadEventEnd - perf.navigationStart,
    firstPaint: performance.getEntriesByType('paint')[0]?.startTime
  };
}, function(err, timing) {
  console.log('Page performance:', timing);
});

// Access geolocation (if available)
browser.executeAsync(function() {
  var callback = arguments[arguments.length - 1];
  
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(
      position => callback({
        lat: position.coords.latitude,
        lng: position.coords.longitude
      }),
      error => callback({error: error.message})
    );
  } else {
    callback({error: 'Geolocation not supported'});
  }
}, function(err, location) {
  console.log('Location:', location);
});

Advanced JavaScript Patterns

Complex JavaScript execution patterns for sophisticated automation.

Usage Examples:

// Wait for condition with JavaScript polling
browser.executeAsync(function() {
  var callback = arguments[arguments.length - 1];
  
  function checkCondition() {
    if (document.querySelector('.dynamic-content') !== null) {
      callback(true);
    } else {
      setTimeout(checkCondition, 100);
    }
  }
  
  checkCondition();
}, function(err, ready) {
  console.log('Dynamic content loaded:', ready);
});

// Inject and execute external script
browser.executeAsync(function() {
  var callback = arguments[arguments.length - 1];
  
  var script = document.createElement('script');
  script.src = 'https://cdn.jsdelivr.net/npm/lodash@4/lodash.min.js';
  script.onload = function() {
    callback(typeof _ !== 'undefined');
  };
  script.onerror = function() {
    callback(false);
  };
  document.head.appendChild(script);
}, function(err, loaded) {
  console.log('Lodash loaded:', loaded);
});

// Complex form validation
browser.execute(function() {
  var form = document.getElementById('contact-form');
  var inputs = form.querySelectorAll('input[required]');
  var validationResults = {};
  
  inputs.forEach(function(input) {
    validationResults[input.name] = {
      value: input.value,
      valid: input.checkValidity(),
      validationMessage: input.validationMessage
    };
  });
  
  return validationResults;
}, function(err, validation) {
  console.log('Form validation results:', validation);
});

// Screenshot trigger with custom logic
browser.execute(function() {
  // Hide sensitive information before screenshot
  var sensitiveElements = document.querySelectorAll('[data-sensitive]');
  sensitiveElements.forEach(function(el) {
    el.style.visibility = 'hidden';
  });
  
  return sensitiveElements.length;
}, function(err, hiddenCount) {
  console.log('Hidden', hiddenCount, 'sensitive elements');
  
  browser.takeScreenshot(function(err, screenshot) {
    // Restore sensitive elements
    browser.execute(function() {
      var sensitiveElements = document.querySelectorAll('[data-sensitive]');
      sensitiveElements.forEach(function(el) {
        el.style.visibility = 'visible';
      });
    });
  });
});

Error Handling and Debugging

Best practices for handling JavaScript execution errors.

Usage Examples:

// Comprehensive error handling
browser.execute(function() {
  try {
    // Potentially problematic code
    var result = someComplexOperation();
    return {success: true, data: result};
  } catch (error) {
    return {
      success: false,
      error: error.message,
      stack: error.stack
    };
  }
}, function(err, result) {
  if (err) {
    console.error('WebDriver error:', err);
  } else if (!result.success) {
    console.error('JavaScript error:', result.error);
  } else {
    console.log('Success:', result.data);
  }
});

// Debug browser state
browser.execute(function() {
  return {
    url: window.location.href,
    readyState: document.readyState,
    activeElement: document.activeElement.tagName,
    errorCount: window.jsErrors ? window.jsErrors.length : 0,
    consoleErrors: window.console._errors || []
  };
}, function(err, debugInfo) {
  console.log('Browser debug info:', debugInfo);
});

Install with Tessl CLI

npx tessl i tessl/npm-wd

docs

browser-sessions.md

configuration.md

element-location.md

index.md

javascript-execution.md

mobile-testing.md

navigation.md

touch-actions.md

user-input.md

waiting.md

window-management.md

tile.json