This My Code
ChromeDriverService service = ChromeDriverService.CreateDefaultService();
service.HideCommandPromptWindow = true;
ChromeOptions cOptions = new ChromeOptions();
String pathToExtension = #"C:\Users\Evrenus\AppData\Local\Google\Chrome\User Data\Default\Extensions\cfhdojbkjhnklbpkdaibdccddilifddb\3.4.1_0";
cOptions.AddArgument("load-extension=" + pathToExtension);
cOptions.AddArgument("--window-size=2000,1190");
cdriver = new ChromeDriver(service, cOptions);
cdriver.Navigate().GoToUrl(link);
int sayi = 0;
foreach (var item in cdriver.WindowHandles)
{
if (sayi == 1)
{
cdriver.SwitchTo().Window(item).Close();
}
++sayi;
}
When i was trigger this code i see chrome my screen.
This application is twitch chat bot and while i streaming (usually game), viewers can open songs from my computer but my computer ALT + TAB
i try this code on my Form Load Event
Selenium Chrome window running in second monitor screen stealing focus
Related
I am working on a C# project where I am trying to send a excel file by WhatsApp. The problem is that whenever I run the code a new instance of command window is open, and a new window is opened for chrome every time I ran the code. Before running the code, I have already log-in to my WhatsApp account and wants to use the same window and tab to avoid logging each time. I have tried to use several ways to stop this but failed to achieve the result. Please correct the code. Please don't mind my bad English.
var options = new ChromeOptions();
options.AddArguments(#"user-data-dir=C:\Users\Umesh Aggarwal\AppData\Local\Google\Chrome\User Data");
IWebDriver driver = new ChromeDriver(#"C:\Users\Umesh Aggarwal\Desktop\chromedriver_win32", options);
////// Navigate to Whatsapp web
driver.Navigate().GoToUrl("https://web.whatsapp.com/");
IReadOnlyCollection<string> windowHandles = driver.WindowHandles;
// Find already opened window with Chrome
string chromeWindow = "";
foreach (string window in windowHandles)
{
driver.SwitchTo().Window(window);
if (driver.Title.Contains("Google Chrome"))
{
chromeWindow = window;
break;
}
}
// Switch to Chrome window
driver.SwitchTo().Window(chromeWindow);
// Get all open tabs in Chrome window
IReadOnlyCollection<string> tabHandles = driver.WindowHandles;
// Find already opened tab of Whatsapp web
string whatsappTab = "";
foreach (string tab in tabHandles)
{
driver.SwitchTo().Window(tab);
if (driver.Title.Contains("Whatsapp"))
{
whatsappTab = tab;
break;
}
}
//// Switch to Whatsapp tab
driver.SwitchTo().Window(whatsappTab);
The problem is that I need to get the PID of IE browser instances so that I can close the IE browser(Working in C#).
I launched the IE browser using Selenium and then used Driver Service class as :-
InternetExplorerDriverService driverdetails = InternetExplorerDriverService.CreateDefaultService();
Console.WriteLine(driverdetails.Port);
The plan is to get the port and then have its child process. I am able to do so using a debugger by entering the value of Port manually. But, the port fetched by driverdetails.Port was not the actual port used by my driver.
Is there any was, I can find the Port for any given driver service?
For IE i have an alternative to launch IE and get the URL with port which says http://localhost:. However, this is not the case with other browsers. My want is to make the generic code and hence I am using the Driver Service object.
As far as I know, the InternetExplorerDriverService's ProcessID property gets the process ID of the running driver service executable, and we can't get the IE browser instance PID through the InternetExplorer webdriver. If you want to get the PID, you could try to use the Process class.
From your description, it seems that you want to close the IE tab or window by using the IE Webdriver. If that is the case, I suggest you could use InternetExplorerDriver WindowHandles to get the opened windows, then use the switchto method to switch the window and check the url or title, finally, call the Close method to close the IE window. Please refer to the following sample code:
private const string URL = #"https://dillion132.github.io/login.html";
private const string IE_DRIVER_PATH = #"D:\Downloads\webdriver\IEDriverServer_x64_3.14.0"; // where the Selenium IE webdriver EXE is.
static void Main(string[] args)
{
InternetExplorerOptions opts2 = new InternetExplorerOptions() { InitialBrowserUrl = "https://www.bing.com", IntroduceInstabilityByIgnoringProtectedModeSettings = true, IgnoreZoomLevel = true };
using (var driver = new InternetExplorerDriver(IE_DRIVER_PATH, opts2))
{
driver.Navigate();
Thread.Sleep(5000);
//execute javascript script
var element = driver.FindElementById("sb_form_q");
var script = "document.getElementById('sb_form_q').value = 'webdriver'; console.log('webdriver')";
IJavaScriptExecutor jse = (IJavaScriptExecutor)driver;
jse.ExecuteScript(script, element);
InternetExplorerDriverService driverdetails = InternetExplorerDriverService.CreateDefaultService(IE_DRIVER_PATH);
Console.WriteLine(driverdetails.Port);
// open multiple IE windows using webdriver.
string url = "https://www.google.com/";
string javaScript = "window.open('" + url + "','_blank');";
IJavaScriptExecutor jsExecutor = (IJavaScriptExecutor)driver;
jsExecutor.ExecuteScript(javaScript);
Thread.Sleep(5000);
//get all opened windows (by using IE Webdriver )
var windowlist = driver.WindowHandles;
Console.WriteLine(windowlist.Count);
//loop through the list and switchto the window, and then check the url
if(windowlist.Count > 1)
{
foreach (var item in windowlist)
{
driver.SwitchTo().Window(item);
Console.WriteLine(driver.Url);
if(driver.Url.Contains("https://www.bing.com"))
{
driver.Close(); //use the Close method to close the window. The Quit method will close the browser window and dispose the webdriver.
}
}
}
Console.ReadKey();
}
Console.ReadKey();
}
I want to make screenshot on webpage which is written in flash
For that I have this code:
ChromeOptions options = new ChromeOptions();
IWebDriver driver = new ChromeDriver(options);
...
// I'm clicking on button whicch opens new browser window
driver.FindElement(By.ClassName("click_me")).Click();
Thread.Sleep(1500);
//switch to new window
driver.SwitchTo().Window(driver.WindowHandles.Last());
//maximize it
driver.Manage().Window.Maximize();
//wait for load
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);
//and then take screenshot
Screenshot sc = ((ITakesScreenshot)driver).GetScreenshot();
sc.SaveAsFile(String.Format(#"{0}\{1}.{2}", Environment.GetFolderPath(Environment.SpecialFolder.Desktop), Guid.NewGuid(), ScreenshotImageFormat.Png), ScreenshotImageFormat.Png);
Here works everything but wait for load. It takes a screenshot of loading screen. What can i do?
//wait for load
WaitForLoading(driver);
private void WaitForLoading(IWebDriver driver)
{
var javascriptExecutor = (IJavaScriptExecutor)driver;
_wait.Until(webDriver => javascriptExecutor.ExecuteScript("return document.readyState").ToString() == "complete");
}
I have written several Selenium Website Tests, however, this is my first with a site that is set to Windows Authentication.
I have been trying with Chrome and IE.
With IE I can successfully login to the site, and I see AutoIt typing and I can see that the browser successfully loads the correct page after login, however, the driver never has a connection to that browser.
With Chrome, I can never find the window to connect with AutoIt.
Using C#. See inline code comments for more specifics on the errors.
try
{
var autoIT = new AutoItX3();
if (IE) //IE Driver - Driver looses connection with the window immediately on Navigate, but AutoIT login works.
//(Driver does work fine if I go to a non-windows authentication site)
{
driver.Navigate().GoToUrl(testConfig.Url);
System.Threading.Thread.Sleep(2000);
//driver.CurrentWindowHandle crashes, 'No Window Exits'
var driverHandles = driver.WindowHandles; //result is 0
var test4 = autoIT.WinActive("Windows Security");
autoIT.WinActivate("Windows Security");
autoIT.Send("zzzzzzz");//Don't need user as it remembers
System.Threading.Thread.Sleep(1000);
autoIT.Send("{TAB}");
autoIT.Send("{ENTER}");
//Visually I can see Browser is logged in and full page loads.
autoIT.WinActivate("EDB Data Manager - Internet Explorer");
var test5 = autoIT.WinGetTitle("EDB Data Manager - Internet Explorer");
System.Threading.Thread.Sleep(2000);
driver.Url = testConfig.Url;
System.Threading.Thread.Sleep(2000);
var driverHandles2 = driver.WindowHandles; //result is still 0
//this will fail
IWebElement userName = driver.FindElement(By.Id("WellsCard"));
//I've tried refreshing or navigating to the url again with no success.
}
else //chrome Driver Driver maintains connection with the window immediately, but AutoIT fails, as I can't find window.
{
driver.Navigate().GoToUrl(testConfig.Url);
System.Threading.Thread.Sleep(2000);
var test7 = autoIT.WinExists("Authentication Required");
var tes8 = autoIT.WinExists("data:, - Google Chrome");
var test9 = autoIT.WinExists("EDB Data Manager - Internet Explorer");
var test10 = autoIT.WinExists("Untitled - Google Chrome");
//None exist, so this will not work.
autoIT.WinActivate("Authentication Required");
autoIT.Send("myUserName");
autoIT.Send("{TAB}");
autoIT.Send("zzzzz");
System.Threading.Thread.Sleep(1000);
autoIT.Send("{TAB}");
autoIT.Send("{ENTER}");
}
}
catch (Exception ex)
{
output.OutputMessage(ex.ToString());
}
I need to know the process ID of the browser (or tab if google chrome) which execute the IWebDriver GoToUrl method.
I found this on stack overflow: Find PID of browser process launched by Selenium WebDriver
However, my browser is already opened. For the worse case, if it's google chrome, I need the process ID of the tab which went on the URL.
Reason
I use Fiddler to capture requests, and when I capture the requests, I can access the process ID. I need to match it with browser which did the GoToUrl.
If you ran the code that executed IWebDriver to start the Chrome browser then you can add more code that will get the PID for you.
You don't state which language you are using. Below is an example you can use for C# and Selenium. There would be the same implementation for other languages (like Java) but I am only working in C#.
Chrome allows you to supply your own user-defined command-line arguments. So you can add an argument named "scriptpid-" with the PID (Windows Process ID) of your currently running program. ChromeDriver passes your argument to Chrome in the command-line. Then using Windows WMI calls retrieve this PID from the command-line of the running Chrome ...
public static IntPtr CurrentBrowserHwnd = IntPtr.Zero;
public static int CurrentBrowserPID = -1;
ChromeOptions options = new ChromeOptions();
options.AddArgument("scriptpid-" + System.Diagnostics.Process.GetCurrentProcess().Id);
IWebDriver driver = new ChromeDriver(options);
// Get the PID and HWND details for a chrome browser
System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName("chrome");
for (int p = 0; p < processes.Length; p++)
{
ManagementObjectSearcher commandLineSearcher = new ManagementObjectSearcher("SELECT CommandLine FROM Win32_Process WHERE ProcessId = " + processes[p].Id);
String commandLine = "";
foreach (ManagementObject commandLineObject in commandLineSearcher.Get())
{
commandLine += (String)commandLineObject["CommandLine"];
}
String script_pid_str = (new Regex("--scriptpid-(.+?) ")).Match(commandLine).Groups[1].Value;
if (!script_pid_str.Equals("") && Convert.ToInt32(script_pid_str).Equals(System.Diagnostics.Process.GetCurrentProcess().Id))
{
CurrentBrowserPID = processes[p].Id;
CurrentBrowserHwnd = processes[p].MainWindowHandle;
break;
}
}
CurrentBrowserHwnd should contain the HWND of your Chrome window.
CurrentBrowserPID should contain the Process ID of your Chrome window.