问题
A few days ago, I had the requirement to make my WebDriver(Chromedriver in that case) switch between 2 tabs on my browser (One of which has been automatically opened by clicking a link).
I was able to implement a solution using the following lines (C#)
var tabs = new List<String>(Driver.WindowHandles);
//Switches to the first tab
Driver.SwitchTo().Window(tabs[0]);
However, I recently came across some implementations that use frames and alerts, which confused me.
The documentation has not been very helpful to me as I still have trouble figuring out use cases for each.
Could you please enlighten me what the difference between Frame and Window is for that purpose ( performance, reliability, cross-platform,... )?
回答1:
Frame :
is a tag in HTML. However The tag is not supported in HTML5.
The <frame> tag defines one particular window (frame) within a <frameset>
Normally, You must have seen Iframe in DOM. It's basically section of a HTML page.
Moreover, If you want to interact any element which is inside a frame , You will have to switch to frame.
How :
SwitchTo().Frame(int frameIndex) : using index
SwitchTo().Frame(IWebElement frameElement) : Select a frame using its previously located OpenQA.Selenium.IWebElement.
SwitchTo().Frame(string frameName) : Select a frame by its name.
Windows :
When you click on any any link and a new tab opens or a new windows itself open that's a window in Selenium.
How : You have already mentioned that in your Post.
Hope this'll be helpful.
回答2:
In Selenium, Window can be different Tab in same browser instance or different browser instance. The context of switch to window is multiple pages or browser instance.
Frame inside web page, so the context of switch to frame is one Page, not multiple pages or browser instances.
回答3:
Window Object
The Window Object represents an open window in a browser.
If a document contain frames ( tags), the browser creates one Window Object for the HTML document and one additional window object for each of the frame it contains.
As per the WebDriver W3C Editor's Draft WebDriver commands happen in the context of either the current browsing context or the current top-level browsing context.
Driver.SwitchTo().Window(windowHandle)
The current top-level browsing context is represented in the protocol by its associated window handle. A top-level browsing context can be selected using the Switch To Window command as follows :
Driver.SwitchTo().Window(windowHandle)
Driver.SwitchTo().Frame(frameReference)
Similarly, a specific browsing context can be selected using the Switch to Frame command.
Driver.SwitchTo().Frame(driver.FindElement(By.XPath("//iframe[contains(@src,'<src_attribute_value>')]")));
来源:https://stackoverflow.com/questions/50393149/what-is-the-difference-between-webdriver-switchto-window-and-webdriver-switc