Nisarg Patel
Nisarg Patel

Reputation: 39

How to Click OK on chrome popup using Selenium Webdriver C#

I'm trying to code below script for clicking OK button through script but fail to do it.

enter image description here

IAlert alert = driver.SwitchTo().Alert();
alert.Accept();

What am I doing wrong, Correct me.

Upvotes: 1

Views: 5027

Answers (2)

Brendan
Brendan

Reputation: 1035

I found an excellent nuget package, AutoItX.Dotnet, that will handle popups in chrome. Link to nuget package - https://www.nuget.org/packages/AutoItX.Dotnet/

Please use the code below as a reference

//This code snippet will fix your specific issue
AutoItX.WinWait("Untitled - Google Chrome", "", 2);
AutoItX.WinActivate("Untitled - Google Chrome");
AutoItX.Send("{Enter}");

//Use code below to switch between buttons/text boxes within the popup
//And send text to text boxes within the popup
AutoItX.Send("{TAB}");
AutoItX.Send("HelloWorld");

You may have to test a bit further to see what keys you need to pass to make this code work seamlessly with each specific popup that you wish to interact with.

Upvotes: 1

Shubham Jain
Shubham Jain

Reputation: 17553

JavascriptExecutor should work for you. Just take care that you should execute it before clicking the event which invoke alert.

C# Code

IWebDriver driver; // assume assigned elsewhere
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
js.ExecuteScript("window.confirm = function(msg) { return true; }");

Java Code

((JavascriptExecutor) driver).executeScript("window.confirm = function(msg) { return true; }");

Note :- do not use it after clicking on event which invoke alert confirmation box. Above code by default set the confirmation box as true means you are accepting/click on ok on all confirmation box on that page if invoked

Hope it will help you :)

Upvotes: 1

Related Questions