.window.switchTo() 建议编辑
将焦点更改为另一个窗口。
要更改焦点的窗口必须通过其服务器分配的窗口句柄指定。要找出窗口句柄,请使用 window.getAllHandles()
命令。
用法
.window.switchTo(windowHandle, [callback])
示例
module.exports = {
'switch to another window': function (browser) {
browser
.navigateTo('https://nightwatch.node.org.cn/__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.node.org.cn/__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 |
字符串 | 服务器分配的窗口句柄,应为 |
回调 可选 |
函数 | 命令完成时要调用的可选回调函数。 |