简体   繁体   English

禁用在 selenium (Node.js) 中打开的选项卡

[英]Disable tabs opened in selenium (Node.js)

Im using the selenium webdriver for node.js and im also loading an extension, loading the extension works fine but when I start my project it goes to the page I want then instantly the extension opens a new tab (Thank you for adding this extension bla bla bla), Im wondering if theres a way to disable tabs that are not opened by myself, ive tried this:我使用 node.js 的 selenium webdriver 并且我还加载了一个扩展,加载扩展工作正常但是当我开始我的项目时它转到我想要的页面然后立即扩展打开一个新选项卡(谢谢你添加这个扩展 bla bla bla ),我想知道是否有办法禁用我自己没有打开的标签,我试过这个:

await driver.get('https://mywebsite.com') //open my initial site
await driver.sleep(1000) //give time for the extension site to open
driver.switchTo(await driver.getAllWindowHandles()[1]) //switch to extension site
await driver.close()
driver.switchTo(await driver.getAllWindowHandles()[0]) //switch back to the main site
//rest of my code

Unfortunately this just does not seem to work, any advice appreciated!不幸的是,这似乎不起作用,任何建议表示赞赏!

There's no way to disable tabs not opened by your script.无法禁用脚本未打开的选项卡。 As long as you don't change window handles, the driver will still be on the original tab.只要您不更改 window 句柄,驱动程序仍将位于原始选项卡上。 You can proceed with the script from there, ignoring the other opened tabs.您可以从那里继续执行脚本,而忽略其他打开的选项卡。

I think the main issue I see with your code is that you are passing parameters to .switchTo() instead of .window() .我认为我在您的代码中看到的主要问题是您将参数传递给.switchTo()而不是.window() It should be driver.switchTo().window(handle);应该是driver.switchTo().window(handle); . .

If you want to find the new window to close it, I wrote that code in this answer .如果你想找到新的 window 来关闭它,我在这个答案中写了那个代码。 All you need to do is to add the .close() line after that code and switch back to the original handle, which you already have in your current code (after fixing with my feedback above).您需要做的就是在该代码之后添加.close()行并切换回您在当前代码中已经拥有的原始句柄(在使用我上面的反馈修复之后)。

Another approach is heavily based on the selenium.dev docs :另一种方法主要基于selenium.dev 文档

// Open the initial site
await driver.get('https://mywebsite.com')

// Store the ID of the original window
const originalWindow = await driver.getWindowHandle();

// Wait for the new window or tab
await driver.wait(async () => (await driver.getAllWindowHandles()).length === 2, 10000);

// Loop through until we find a new window handle
const windows = await driver.getAllWindowHandles();
windows.forEach(async handle => {
  if (handle !== originalWindow) {
    await driver.switchTo().window(handle);
  }
});

await driver.close()
await driver.switchTo().window(originalWindow);
// Rest of the code

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM