Search code examples
selenium-webdriveriframeselenide

Method to return a WebElement inside an iframe


I'm trying to create a method in my page class that returns a ElementsCollection (I'm using Selenide, so this is like a list of WebElements). The issue is that the WebElements are inside an iframe, so what I'm trying to do is:

    public ElementsCollection myWebElements() {
        switchTo().frame(contentIFrame());
        final ElementsCollection myWebElements = $$("div.locatorToMyElements");
        switchTo().defaultContent();

        return MyWebElements;
    }

I can see that up to switchTo().defaultContent() everything works fine: The list of elements is stored in MyWebElements as expected. But, when the switchTo().defaultContent() line is executed, then what was stored in the myWebElements ElementsCollection is lost and I get this error.

Unable to evaluate the children renderer expression Method threw 'org.openqa.selenium.NoSuchElementException' exception.

Any help will be welcomed. Thanks!


Solution

  • The issue you have is happened, because you changed context to defaultContext.

    You can manipulate elements only inside the same context where they were created.

    In your case you got ElementsCollection inside your frame. Then you are switching to another context. Collection exists, but when you try to interact with it, it would throw exception as far as it's methods would be called in current context (and there are no your elements in it, they are placed in iframe).

    So, to resolve your issue, just switch to defaultContext after actions with elements.

    Like another option, you can implement chain construction inside your framework when every class instance would be sensitive to context.