關閉視窗
WebDriver API 中的 Close Window(關閉視窗) 命令會關閉當前的頂級瀏覽上下文(視窗或標籤頁),並返回當前開啟的 WebWindow 列表。如果關閉的是最後一個視窗,WebDriver 會話將被隱式刪除。會話結束後,後續命令將導致無效會話 ID 錯誤。
語法
| 方法 | URI 模板 |
|---|---|
DELETE |
/session/{session id}/window |
URL 引數
session id-
會話的識別符號。
錯誤
- 無效的會話 ID
-
會話不存在。
- 意外的 alert 開啟
-
使用者提示(如
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#
cs
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 |
瀏覽器相容性
載入中…
另見
- 切換到視窗 命令
- 獲取視窗控制代碼 命令
- 獲取視窗控制代碼列表 命令