Back to Repositories

Validating JavaScript Injection Timing in Frame Contexts for NW.js

This test suite validates the injection of JavaScript code at the end of document loading in both main window and iframe contexts using Selenium WebDriver with NW.js. The test ensures proper script injection timing and DOM manipulation across different window contexts.

Test Coverage Overview

The test provides comprehensive coverage of JavaScript injection functionality in NW.js, specifically targeting the inject_end feature.

Key areas tested include:
  • Main window script injection verification
  • Iframe context script injection validation
  • DOM element presence confirmation
  • Cross-context injection consistency

Implementation Analysis

The testing approach utilizes Selenium WebDriver with Chrome options configured for NW.js application testing. The implementation follows a sequential verification pattern, first checking the main window context before switching to the iframe context.

Technical patterns include:
  • WebDriver initialization with custom Chrome options
  • Element location using multiple strategies (id, tag name)
  • Frame context switching
  • Attribute value verification

Technical Details

Testing tools and configuration:
  • Selenium WebDriver with Chrome driver
  • Python test framework
  • Custom NW.js utility imports
  • Environment-based ChromeDriver path configuration
  • Implicit wait timing of 5 seconds
  • Try-finally block for proper driver cleanup

Best Practices Demonstrated

The test exhibits several testing best practices for browser automation and cross-context verification.

Notable practices include:
  • Proper resource cleanup in finally block
  • Explicit assertions for verification
  • Consistent element presence checking
  • Cross-frame testing methodology
  • Proper wait time implementation

nwjs/nwJs

test/sanity/issue4791-injectend-iframe/test.py

            
import time
import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from nw_util import *

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("nwapp=" + os.path.dirname(os.path.abspath(__file__)))

driver = webdriver.Chrome(executable_path=os.environ['CHROMEDRIVER'], chrome_options=chrome_options)
driver.implicitly_wait(5)
try:
    print(driver.current_url)
    result = driver.find_element_by_id('inject_end').get_attribute('innerHTML')
    print('inject_js_end: %s' % result)
    assert('success' in result)
    elems = driver.find_elements_by_tag_name('h1')
    assert(len(elems) == 1)
    driver.switch_to.frame(driver.find_element_by_tag_name("iframe"))
    result = driver.find_element_by_id('inject_end').get_attribute('innerHTML')
    print('inject_js_end in iframe: %s' % result)
    assert('success' in result)
    elems = driver.find_elements_by_tag_name('h1')
    assert(len(elems) == 1)
finally:
    driver.quit()