All Projects → Georgegriff → Query Selector Shadow Dom

Georgegriff / Query Selector Shadow Dom

Licence: mit
querySelector that can pierce Shadow DOM roots without knowing the path through nested shadow roots. Useful for automated testing of Web Components. Production use is not advised, this is for test environments/tools such as Web Driver, Playwright, Puppeteer

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to Query Selector Shadow Dom

Protractor
E2E test framework for Angular apps
Stars: ✭ 8,792 (+7545.22%)
Mutual labels:  selenium, webdriver, protractor
Tib
Easy e2e browser testing in Node
Stars: ✭ 64 (-44.35%)
Mutual labels:  selenium, webdriver, puppeteer
page-modeller
⚙️ Browser DevTools extension for modelling web pages for automation.
Stars: ✭ 66 (-42.61%)
Mutual labels:  webdriver, selenium, puppeteer
Marionette
Selenium alternative for Crystal. Browser manipulation without the Java overhead.
Stars: ✭ 119 (+3.48%)
Mutual labels:  selenium, webdriver, puppeteer
Memedensity
CLI tool to let you know amount of memes in facebook feed.
Stars: ✭ 44 (-61.74%)
Mutual labels:  selenium, webdriver
Edge Selenium Tools
An updated EdgeDriver implementation for Selenium 3 with newly-added support for Microsoft Edge (Chromium).
Stars: ✭ 41 (-64.35%)
Mutual labels:  selenium, webdriver
Whalesong
Whalesong is an asyncio python library to manage WebApps remotely. Currently WhatsappWeb is implemented
Stars: ✭ 46 (-60%)
Mutual labels:  selenium, puppeteer
Python web framework
这是一个关于python的WebUI自动化测试的项目,之前用的是unittest测试框架,现在改成pytest测试框架,Python+PageObject+Pytest
Stars: ✭ 49 (-57.39%)
Mutual labels:  selenium, webdriver
Java.appium
Mobile test automation using Appium in Java
Stars: ✭ 59 (-48.7%)
Mutual labels:  selenium, webdriver
Custom Element
A base class for Web Components (Custom Elements) which provides simple data binding.
Stars: ✭ 60 (-47.83%)
Mutual labels:  webcomponents, shadow-dom
Cabbie
WebDriver for the masses
Stars: ✭ 70 (-39.13%)
Mutual labels:  selenium, webdriver
Xebium
Xebium provides Selenium (webdriver) bindings for FitNesse, with Selenium-IDE support
Stars: ✭ 73 (-36.52%)
Mutual labels:  selenium, webdriver
Wd
Use WebDriver from the command line
Stars: ✭ 31 (-73.04%)
Mutual labels:  selenium, webdriver
Reactshadow
🔰 Utilise Shadow DOM in React with all the benefits of style encapsulation.
Stars: ✭ 948 (+724.35%)
Mutual labels:  webcomponents, shadow-dom
Arquillian Extension Drone
Arquillian Drone provides a simple way to write functional tests for web apps. Drone brings the power of WebDriver into the Arquillian, and the power of Arquillian to WebDriver.
Stars: ✭ 45 (-60.87%)
Mutual labels:  selenium, webdriver
Marionette client
Mozilla's Gecko Marionette client in golang
Stars: ✭ 21 (-81.74%)
Mutual labels:  selenium, webdriver
Wdio Workshop
WebdriverIO Workshop
Stars: ✭ 20 (-82.61%)
Mutual labels:  selenium, webdriver
Seleniumwithcucucumber
In this project we will discuss working Selenium with cucumber
Stars: ✭ 104 (-9.57%)
Mutual labels:  selenium, webdriver
E2e Experiment
A demo project with Spring Boot / Angular application and e2e tests
Stars: ✭ 9 (-92.17%)
Mutual labels:  selenium, webdriver
Singlefilez
Web Extension for Firefox/Chrome/MS Edge and CLI tool to save a faithful copy of an entire web page in a self-extracting HTML/ZIP polyglot file
Stars: ✭ 882 (+666.96%)
Mutual labels:  selenium, puppeteer

Build Status npm version codecov

query-selector-shadow-dom

querySelector that can pierce Shadow DOM roots without knowing the path through nested shadow roots. Useful for automated testing of Web Components e.g. with Selenium, Puppeteer.

ko-fi

// available as an ES6 module for importing in Browser environments

import { querySelectorAllDeep, querySelectorDeep } from 'query-selector-shadow-dom';

What is a nested shadow root?

Image of Shadow DOM elements in dev tools You can see that .dropdown-item:not([hidden]) (Open downloads folder) is several layers deep in shadow roots, most tools will make you do something like

document.querySelector("body > downloads-manager").shadowRoot.querySelector("#toolbar").shadowRoot.querySelector(".dropdown-item:not([hidden])")

EW!

with query-selector-shadow-dom:

import { querySelectorAllDeep, querySelectorDeep } from 'query-selector-shadow-dom';
querySelectorDeep(".dropdown-item:not([hidden])");

API

  • querySelectorAllDeep - mirrors querySelectorAll from the browser, will return an Array of elements matching the query
  • querySelectorDeep - mirrors querySelector from the browser, will return the first matching element of the query.
  • collectAllElementsDeep - collects all elements on the page, including shadow dom

Both of the methods above accept a 2nd parameter, see section Provide alternative node. This will change the starting element to search from i.e. it will find ancestors of that node that match the query.

Plugins

WebdriverIO

This plugin implements a custom selector strategy: https://webdriver.io/docs/selectors.html#custom-selector-strategies

// make sure you have selenium standalone running
const { remote } = require('webdriverio');
const { locatorStrategy } = require('query-selector-shadow-dom/plugins/webdriverio');

(async () => {
    const browser = await remote({
        logLevel: 'error',
        path: '/wd/hub',
        capabilities: {
            browserName: 'chrome'
        }
    })

    // The magic - registry custom strategy
    browser.addLocatorStrategy('shadow', locatorStrategy);


    // now you have a `shadow` custom locator.

    // All elements on the page
    await browser.waitUntil(() => browser.custom$("shadow", ".btn-in-shadow-dom"));
    const elements = await browser.$$("*");

    const elementsShadow = await browser.custom$$("shadow", "*");

    console.log("All Elements on Page Excluding Shadow Dom", elements.length);
    console.log("All Elements on Page Including Shadow Dom", elementsShadow.length);


    await browser.url('http://127.0.0.1:5500/test/')
    // find input element in shadow dom
    const input = await browser.custom$('shadow', '#type-to-input');
    // type to input ! Does not work in firefox, see above.
    await input.setValue('Typed text to input');
    // Firefox workaround
    // await browser.execute((input, val) => input.value = val, input, 'Typed text to input')

    await browser.deleteSession()
})().catch((e) => console.error(e))

How is this different to shadow$

shadow$ only goes one level deep in a shadow root.

Take this example. Image of Shadow DOM elements in dev tools You can see that .dropdown-item:not([hidden]) (Open downloads folder) is several layers deep in shadow roots, but this library will find it, shadow$ would not. You would have to construct a path via css or javascript all the way through to find the right element.

const { remote } = require('webdriverio')
const { locatorStrategy } = require('query-selector-shadow-dom/plugins/webdriverio');

(async () => {
    const browser = await remote({capabilities: {browserName: 'chrome'}})

    browser.addLocatorStrategy('shadow', locatorStrategy);

    await browser.url('chrome://downloads')
    const moreActions = await browser.custom$('shadow', '#moreActions');
    await moreActions.click();
    const span = await browser.custom$('shadow', '.dropdown-item:not([hidden])');
    const text = await span.getText()
    // prints `Open downloads folder`
    console.log(text);

    await browser.deleteSession()
})().catch((e) => console.error(e))

Known issues

There are some webdriver examples available in the examples folder of this repository. WebdriverIO examples

Puppeteer

Update: As of 5.4.0 Puppeteer now has a built in shadow Dom selector, this module might not be required for Puppeteer anymore. They don't have any documentation: https://github.com/puppeteer/puppeteer/pull/6509

There are some puppeteer examples available in the examples folder of this repository.

Puppeteer examples

Playwright

Update: as of Playwright v0.14.0 their CSS and text selectors work with shadow Dom out of the box, you don't need this library anymore for Playwright.

Playwright works really nicely with this package.

This module exposes a playwright selectorEngine: https://github.com/microsoft/playwright/blob/main/docs/api.md#selectorsregisterenginefunction-args

const { selectorEngine } = require("query-selector-shadow-dom/plugins/playwright");
const playwright = require('playwright');

 await selectors.register('shadow', createTagNameEngine);
...
  await page.goto('chrome://downloads');
  // shadow= allows a css query selector that automatically pierces shadow roots.
  await page.waitForSelector('shadow=#no-downloads span', {timeout: 3000})

For a full example see: https://github.com/Georgegriff/query-selector-shadow-dom/blob/main/examples/playwright

Protractor

This project provides a Protractor plugin, which can be enabled in your protractor.conf.js file:

exports.config = {
    plugins: [{
        package: 'query-selector-shadow-dom/plugins/protractor'
    }],
    
    // ... other Protractor-specific config
};

The plugin registers a new locator - by.shadowDomCss(selector /* string */), which can be used in regular Protractor tests:

element(by.shadowDomCss('#item-in-shadow-dom'))

The locator also works with Serenity/JS tests that use Protractor under the hood:

import 'query-selector-shadow-dom/plugins/protractor';
import { Target } from '@serenity-js/protractor'
import { by } from 'protractor';

const ElementOfInterest = Target.the('element of interest')
    .located(by.shadowDomCss('#item-in-shadow-dom'))

See the end-to-end tests for more examples.

Examples

Provide alternative node

    // query from another node
    querySelectorShadowDom.querySelectorAllDeep('child', document.querySelector('#startNode'));
    // query an iframe
    querySelectorShadowDom.querySelectorAllDeep('child', iframe.contentDocument);

This library does not allow you to query across iframe boundaries, you will need to get a reference to the iframe you want to interact with. If your iframe is inside of a shadow root you could cuse querySelectorDeep to find the iframe, then pass the contentDocument into the 2nd argument of querySelectorDeep or querySelectorAllDeep.

Chrome downloads page

In the below examples the components being searched for are nested within web components shadowRoots.

// Download and Paste the lib code in dist into chrome://downloads console to try it out :)

console.log(querySelectorShadowDom.querySelectorAllDeep('downloads-item:nth-child(4) #remove'));
console.log(querySelectorShadowDom.querySelectorAllDeep('#downloads-list .is-active a[href^="https://"]'));
console.log(querySelectorShadowDom.querySelectorDeep('#downloads-list div#title-area + a'));

Shady DOM

If using the polyfills and shady DOM, this library will still work.

Importing

  • Shipped as an ES6 module to be included using a bundler of your choice (or not).
  • ES5 version bundled ontop the window as window.querySelectorShadowDom available for easy include into a test framework

Running the code locally

npm install

Running the tests

npm test

Running the tests in watch mode

npm run watch

Running the build

npm run build

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].