關閉視窗
WebDriver API 的關閉視窗命令關閉當前頂級瀏覽上下文(視窗或選項卡)並返回當前開啟的WebWindow列表。如果它是最後一個被關閉的視窗,則 WebDriver 會話將隱式刪除。因此,會話結束後的後續命令將導致無效會話 ID錯誤。
語法
| 方法 | URI 模板 |
|---|---|
DELETE |
/session/{session id}/window |
URL 引數
會話 ID-
會話的識別符號。
錯誤
- 無效會話 ID
-
會話不存在。
- 意外的警告開啟
-
使用者提示(例如
window.alert)阻止命令執行,直到處理為止。
示例
Python
python
from selenium import webdriver
session = webdriver.Firefox()
original_window = session.window_handle
new_window = session.execute_script("return window.open()")
session.switch_to.window(new_window)
session.close()
session.switch_to.window(original_window)
C#
cpp
using OpenQA.Selenium.Firefox;
namespace MDNWebDriverExamples
{
class Example
{
public static void Main(string[] args)
{
FirefoxDriver session = new FirefoxDriver();
string original_window = session.CurrentWindowHandle;// Optional if you want to store the handle in a variable
session.ExecuteScript("window.open()");
session.SwitchTo().Window(session.WindowHandles[1]); // Switch to the second window
session.Close(); // Close current window
session.SwitchTo().Window(session.WindowHandles[0]); // Switch back to the first window
}
}
}
規範
| 規範 |
|---|
| WebDriver # close-window |
瀏覽器相容性
BCD 表格僅在瀏覽器中載入