How to swith to iframe inside shadow dom with selenium

此生再无相见时 提交于 2021-02-08 09:53:39

问题


Application under test is based on Electron (version 9.1.1) written as desktop application for Linux. In electron there are custom tag <webview> that is quote "The webview tag is essentially a custom element using shadow DOM to wrap an iframe element inside it."

I can access shadow dom and get iframe as WebElement out of it with Java selenim(version 3.141.59).

But swithcing to iframe still left me on parent context.

And my question is:

HOW TO SWITH TO IFRAME INSIDE SHADOW DOM?

//getting webdriver
WebDriver driver = WebDriverRunner.getWebDriver();
JavascriptExecutor js = (JavascriptExecutor) driver;

//acquire shadow dom WebElement 
WebElement shadowDom = (WebElement) js.executeScript("return arguments[0].shadowRoot", driver.findElement(By.tagName("webview")));

//acquire iframe WebElement 
WebElement iframe = shadowDom.findElement(By.tagName("iframe"));

//trying to swith to iframe inside shadow DOM, but still at parent context because can't find element that exist in iframe
driver.switchTo().frame(iframe);

//obviously produce NoSuchElementException
driver.findElement(By.xpath(".//label[text()='Columns']"));

This is HTML of the page, and I can get html of webview executing in devtools command document.querySelector('webview').openDevTools(); That's why I'm sure that .//label[text()='Columns'] exist.


UPD I'm connecting to electron application through exposed port, maybe this is kind of issue?

    public WebDriver createDriver(DesiredCapabilities desiredCapabilities) 

        ChromeOptions options = new ChromeOptions();
        options.setExperimentalOption("debuggerAddress", "localhost:8315");
        options.setAcceptInsecureCerts(true);
        options.merge(desiredCapabilities);

        return new ChromeDriver(options);
    }

回答1:


Actually answer was pretty simple. You need just explicitly declare that you want webview to appear in the list of window handles.

Here is official chromedriver docs link and capabilities name is windowTypes

In java code it will be looked like this

ChromeOptions options = new ChromeOptions();
List<String> webview = Collections.singletonList("webview");
options.setExperimentalOption("windowTypes", webview);

WebDriver driver = new ChromeDriver(options);

//after that you can just switch to is
driver.switchTo().window("yourHandle");

//and work with it as usual
driver.findElement(By.xpath(".//label[text()='Columns']"));



来源:https://stackoverflow.com/questions/63225306/how-to-swith-to-iframe-inside-shadow-dom-with-selenium

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!