如何为Polymer元素阴影dom元素指定选择器?

时间:2018-01-30 15:05:37

标签: puppeteer

我有一个基于聚合物的网络应用程序,我想用Puppeteer进行测试。

当多个聚合物组件相互嵌入时,为案例编写选择器的适当方法是什么?

布局将是:

app> comp1> comp2> target_element

所有'>'标志着一个新的影子dom边界。

如果我想在链的末尾测试target_element,那么正确的选择器是什么?

1 个答案:

答案 0 :(得分:2)

事实证明,这不是easy to select element in shadow domAchim Weimertget pierce select through shadow dom显示了一些解决方法。他的方法适用于https://shop.polymer-project.org/中的app-header

const puppeteer = require('puppeteer');

const shadowSelectorFn = (el, selector) => el.shadowRoot.querySelector(selector);

const queryDeep = async (page, ...selectors) => {
    if (!selectors || selectors.length === 0) {
        return;
    }

    const [ firstSelector, ...restSelectors ] = selectors;
    let parentElement = await page.$(firstSelector);
    for (const selector of restSelectors) {
        parentElement = await page.evaluateHandle(shadowSelectorFn, parentElement, selector);
    }

    return parentElement;
};


(async () => {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto('https://shop.polymer-project.org/');


    const app = await page.$('shop-app');
    console.log(app);

    // you can not simply wait for element inside shadow dom
    // it's up to you how you detect if this element is ready
    await page.waitFor(2000);

    const header = await queryDeep(
        page,
        'shop-app', 'app-header'
    );
    console.log(header);

    await browser.close();
})();

值得一提的是,没有简单的方法来检测app-header元素何时准备就绪。您可以在一个循环中以一些时间间隔检查此元素,或者您应该寻找其他解决方案。