.window.switchTo() 建議編輯
將焦點變更為另一個視窗。
要變更焦點的視窗必須由其伺服器指派的視窗控制代碼指定。若要找出視窗控制代碼,請使用 window.getAllHandles()
指令。
用法
.window.switchTo(windowHandle, [callback])
範例
module.exports = {
'switch to another window': function (browser) {
browser
.navigateTo('https://nightwatch.dev.org.tw/__e2e/window/')
.click('#openWindowBttn')
.waitUntil(function () {
// wait until window handle for the new window is available
return new Promise((resolve) => {
browser.window.getAllHandles(function (result) {
resolve(result.value.length === 2);
});
});
})
.perform(async function () {
const originalWindow = await browser.window.getHandle();
const allWindows = await browser.window.getAllHandles();
// loop through to find the new window handle
for (const windowHandle of allWindows) {
if (windowHandle !== originalWindow) {
await browser.window.switchTo(windowHandle);
break;
}
}
const currentWindow = await browser.window.getHandle();
browser.assert.notEqual(currentWindow, originalWindow);
});
},
'switch to another window with ES6 async/await': async function (browser) {
await browser.navigateTo('https://nightwatch.dev.org.tw/__e2e/window/');
await browser.click('#openWindowBttn');
// wait until window handle for the new window is available
await browser.waitUntil(async function () {
const windowHandles = await browser.window.getAllHandles();
return windowHandles.length === 2;
});
const originalWindow = await browser.window.getHandle();
const allWindows = await browser.window.getAllHandles();
// loop through available windows to find the new window handle
for (const windowHandle of allWindows) {
if (windowHandle !== originalWindow) {
await browser.window.switchTo(windowHandle);
break;
}
}
const currentWindow = await browser.window.getHandle();
await browser.assert.notEqual(currentWindow, originalWindow);
}
}
參數
名稱 | 類型 | 描述 |
---|---|---|
windowHandle |
字串 | 伺服器指派的視窗控制代碼,應該是在呼叫 |
callback 選用 |
函式 | 指令完成時要呼叫的選用回呼函式。 |