简体   繁体   中英

Selenium Webdriver on PowerShell SendKey function send keys on current active window, not the Selenium invoked browser

I'm writing a PowerShell script that runs the Selenium Webdriver. What I'm planning to do is open up a page, open x tabs more, return to the first tab, do something, go to the next tab, do something, and so on.

But when I use the SendKeys on the code to send Ctrl+T to open up a new tab, unless the Selenium invoked browser is active, it sends Ctrl+T to my active window, (eg, Powershell ISE (What it does is it opens a new PowerShell tab)).

I hope you can help me with this, guys.

Here's the code:

Add-Type -AssemblyName "System.Windows.Forms"

Set-Location "$PSScriptRoot\selenium-dotnet-2.53.0\net35"
[System.Reflection.Assembly]::LoadFrom("$PSScriptRoot\selenium-dotnet-2.53.0\net35\Selenium.WebDriverBackedSelenium.dll")
[System.Reflection.Assembly]::LoadFrom("$PSScriptRoot\selenium-dotnet-2.53.0\net35\ThoughtWorks.Selenium.Core.dll")
[System.Reflection.Assembly]::LoadFrom("$PSScriptRoot\selenium-dotnet-2.53.0\net35\WebDriver.dll")
[System.Reflection.Assembly]::LoadFrom("$PSScriptRoot\selenium-dotnet-2.53.0\net35\WebDriver.Support.dll")

$servers = `
"http://facebook.com", `
"http://google.com"

$driver = New-Object "OpenQA.Selenium.FireFox.FirefoxDriver"
$driver.Manage().Window.Maximize();

$actions = New-Object OpenQA.Selenium.Interactions.Actions($driver)

for ($i = 0; $i -lt $($servers.Length); $i++){
    $driver.Navigate().GoToUrl($servers[$i])
    if ($i + 1 -ne $($servers.Length)) {
        $driver.FindElementByCssSelector("body").SendKeys($body,[System.Windows.Forms.SendKeys]::SendWait("^t")) | Out-Null
    }
}

foreach($server in $servers){
    $driver.FindElementByCssSelector("body").SendKeys($body,       [System.Windows.Forms.SendKeys]::SendWait("^{TAB}")) | Out-Null
    $driver.SwitchTo().DefaultContent()
}

Instead of the two SendKeys commands, try using:

    $driver.executeScript("window.open('http://YourDomainGoesHere.com/', '_blank')")

Works with IE, but have not tried it myself with Firefox.

You could probably check Appactive() method or check the current active window and proceed.

EDIT : you can kill other browser sessions before selenium opens one and make I active windows using Appactive.

Regards,

kvprasoon

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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