Tharaka Deshan Tharaka Deshan - 5 months ago 149
Java Question

Selenium WebDriver get Current frame before switch

I have a custom action to find elements, by switching in the certain iFrame.
It uses the following native action:

driver.switchTo().frame(requested_frame)

Currently I am switching back to the default content every-time before switch to the exact iframe.

Now I need to improve it's performance by following scnario:


  • Check the current content/frame

  • if
    requested_frame=currentFrame
    then No need to switch

  • if
    requested_frame=null
    then switch to default (if
    currentFrame=default
    then again no need to switch)

  • if
    requested_frame!=null && requested_frame!=currentFrame
    then switch to default, and switch to
    requested_frame
    frame.



So all I need now is to get the Current Frame. Is there any way I can get it?

Answer

You need to implement as below approach :-

String frame = 'your frame';
String currentFrame = null;
// make this currentFrame as global

if ((null != frame) && (!"".equals(frame))) {
        if (!framesPath.equals(currentFrame)) {
            switchToFrame(frame);
            currentFrame = frame;
        }
    } else {
        currentFrame = "";
        webDriver.switchTo().defaultContent();
    }

public void switchToFrame(String frame) {
    webDriver.switchTo().defaultContent();
    webDriver.switchTo().frame(frame);
}

Hope it will handle your all conditions..:)

Comments