c# Selenium WebDriver - How to disable notifications on Facebook Page? - c#

I am a beginner in Selenium WebDriver, and I have a problem with poping out notification on Facebook page while I'm trying to log in. I searched a lot, but i did not find anyhing usefull. I found code in java, convert into C# but it didn't work.(I hope that a did it properly) I tried something like this, but nothing. Please, help with this if you can.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Dictionary<string, object> hash = new Dictionary<string, object>();
hash.Add("profile.default_content_setting_values.notifications", 2);
ChromeOptions op = new ChromeOptions();
op.AddAdditionalCapability("hash",hash);
IWebDriver driver = new ChromeDriver("path to googlewebdriver");
driver.Url = "http://facebook.com";
driver.Manage().Window.Maximize();
driver.FindElement(By.Id("email")).SendKeys("my email");
driver.FindElement(By.Id("pass")).SendKeys("mypassw" + Keys.Enter);
driver.FindElement(By.XPath("//*[#id='content_container']")).Click();
}
}
}

If you simply want to disable "all" notification on chrome browser, you can use switch --disable-notifications
Code in C# to launch chrome with this switch:
ChromeOptions options = new ChromeOptions();
options.AddArguments("--disable-extensions"); // to disable extension
options.AddArguments("--disable-notifications"); // to disable notification
options.AddArguments("--disable-application-cache"); // to disable cache
driver = new ChromeDriver(options);
Here's list of switches available for chrome browser: Chromium Comamnd Line Switches
Alternatively, you have options to handle alert by using this code statement:
options.UnhandledPromptBehavior = UnhandledPromptBehavior.Dismiss;
You have other options available here to accept, dismiss, ignore etc.

To disable the annoying "some-annoying-website wants to: 🔔 Show notifications", set your ChromeOptions like this:
ChromeOptions options = new ChromeOptions();
options.AddUserProfilePreference("profile.default_content_setting_values.notifications", 2);
And pass it to your ChromeDriver:
using (var chrome = new ChromeDriver(options)) ...

ChromeOptions op = new ChromeOptions();
op.AddArguments("--disable-notifications");
Most importantly need to check the versions of Chrome Driver. Some versions it may not support.

Related

C# Automation Edge Browser - using Edge Driver - auto testing program - Failure: No matching capabilities found (SessionNotCreated)

Greetings stackoverflow community,
I am trying to compile and run the programcode from this website:
https://social.msdn.microsoft.com/Forums/en-US/7bdafd2a-be91-4f4f-a33d-6bea2f889e09/c-sample-for-automating-ms-edge-chromium-browser-using-edge-web-driver
I followed all the instructions listed in the link and set my paths were I wanted them.
The program and the edge driver starts running, but then an error appears.
"An error exeption "System.InvalidOperationException" appeared in WebDriver.dll.
Further Inforamtion: session not created: No matching capabilities found (SessionNotCreated)"
This is the code from my program, more or less copied from the link above:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Edge;
using OpenQA.Selenium.Remote;
using OpenQA.Selenium.Support.UI;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
var anaheimService = ChromeDriverService.CreateDefaultService(#"C:\edgedriver_win64", "msedgedriver.exe");
// user need to pass the driver path here....
var anaheimOptions = new ChromeOptions
{
// user need to pass the location of new edge app here....
BinaryLocation = #"
C: \Program Files(x86)\Microsoft\Edge\Application\msedge.exe "
};
IWebDriver driver = new ChromeDriver(anaheimService, anaheimOptions); -- error appears at this line
driver.Navigate().GoToUrl("https: //google.com/");
Console.WriteLine(driver.Title.ToString());
driver.Close();
}
}
}
I would really appreciate your help!
Best Regards
Max
The article you refer to is a bit out of date. Now we don't need to use ChromeDriver to automate Edge. You can refer to the official doc about how to use WebDriver to automate Microsoft Edge.
I recommend using Selenium 4. Here I install Selenium 4.1.0 NuGet package and the sample C# code is like below:
using System;
using OpenQA.Selenium.Edge;
namespace WebDriverTest
{
class Program
{
static void Main(string[] args)
{
var options = new EdgeOptions();
options.BinaryLocation = #"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe";
var driver = new EdgeDriver(#"C:\edgedriver_win64", options);
driver.Navigate().GoToUrl("https://www.google.com");
Console.WriteLine(driver.Title.ToString());
driver.Close();
}
}
}

C# SELENIUM: Can't access URL after setting custom FIREFOX profile

I am trying to connect to profile, its successfully connect to custom firefox profile, but the problem after that is command FirefoxDriver driver = new FirefoxDriver(options); no more works, works only if i remove options then no custom profile.
the before last line returns error OpenQA.Selenium.WebDriverException: 'Process unexpectedly closed with status 0' or The HTTP request to the remote WebDriver timed out after 60 seconds, it only works if I remove options inside FirefoxDriver: FirefoxDriver driver = new FirefoxDriver(options);
Also, doing options.AddArgument("-profile" + "C:\Users\Chill\AppData\Roaming\Mozilla\Firefox\Profiles\5k2mdm2k.myprofile"); instead of spliting the 2 arguments does not launch firefox in the right profile.
Or even options.AddArgument("no-sandbox") or options.AddArgument("-no-sandbox") or options.AddArgument("--no-sandbox") doesn't works, also --profile instead of -profile does not open the right profile also, here is my code anyway:
using System;
using OpenQA.Selenium; // nuget package name: Selenium.WebDriver
using OpenQA.Selenium.Firefox; // nuget package name: Selenium.WebDriver.GeckoDriver
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
FirefoxOptions options = new FirefoxOptions();
options.AddArgument("-profile");
options.AddArgument(#"C:\Users\Chill\AppData\Roaming\Mozilla\Firefox\Profiles\5k2mdm2k.myprofile"); /* type about:profiles in firefox bar to create and manage firefox profiles, from there you will see which profile used, make sure to not use the default one and use root directory */
FirefoxDriver driver = new FirefoxDriver(options); /* code stops here and puts error after closing browser or waiting until it close itself after 60 sec */
driver.Navigate().GoToUrl("https://www.google.com/"); /* can only reach this part of code if i remove turn FirefoxDriver(options); to FirefoxDriver(); on the line upper, but no more custom profile so */
}
}
}
Hope you can help im blocked on this step for 3 days
Using these nugget versions:
<PackageReference Include="Selenium.Firefox.WebDriver" Version="0.27.0" />
<PackageReference Include="Selenium.WebDriver" Version="4.0.0-beta4" />
This works for me:
using OpenQA.Selenium.Firefox;
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
var options = new FirefoxOptions();
var profile = new FirefoxProfile(#"C:\Users\CatalinR\AppData\Roaming\Mozilla\Firefox\Profiles\f9n067l1.default");
options.Profile = profile;
var driver = new FirefoxDriver(options);
driver.Navigate().GoToUrl("https://www.google.com/");
}
}
}

IE in Private Mode using Selenium C#

I want to open IE in Private mode to run the set of test cases. The browser is not opening. It shows error as
The HTTP request to the remote WebDriver server for URL {URL} timed out after 60 seconds
Sample code:
InternetExplorerOptions options = new InternetExplorerOptions()
{
ForceCreateProcessApi = true,
BrowserCommandLineArguments = "-private",
};
IWebDriver driver = new InternetExplorerDriver("C:\\Reports", options);
driver.Navigate().GoToUrl("https://www.google.com");
Also I have changed the TabProcGrowth as 0 in Registry Editor.
How to open IE in private mode to run the test case? Anything I want to update in my code. Thanks in advance.
This is how I manage to launch it:
Set the TabProcGrowth as 0 in Registry Editor.
Get the Selenium.WebDriver.IEDriver64 nugget instead of the normal 32 and build the project
Get the IEDriverServer64.exe from bin\Debug\netcoreapp3.1 (the output folder where this file is generated depends on your TargetFramework: .netcore or .netstandard)
Rename that file into IEDriverServer.exe and put it somewhere in a folder
Create the driver instance using the path to that folder. In my case, I created a folder in the project and pointed there
Project: Solution Explorer View
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.IE;
using System.IO;
namespace InternetExplorerPrivate
{
public class Tests
{
public IWebDriver driver;
[SetUp]
public void Setup()
{
InternetExplorerOptions options = new InternetExplorerOptions();
options.ForceCreateProcessApi = true;
options.IntroduceInstabilityByIgnoringProtectedModeSettings = true;
options.BrowserCommandLineArguments = "-private";
driver = new InternetExplorerDriver(Path.GetFullPath(#"..\..\..\IEDriver"), options);
}
[Test]
public void Test1()
{
driver.Navigate().GoToUrl("https://stackoverflow.com/");
}
}
}

not working Selenium Webdriver C# Sendkeys (Keys.control+"t") for newtab [duplicate]

This question already has answers here:
What is the fastest way to open urls in new tabs via Selenium - Python?
(2 answers)
Closed 4 years ago.
I want to create new tab this.windowfirefox in selenium c#
try with 3 solution but not working for me.
firefox and webdrive is last verison and update.
.netframework 4.5
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using System.Threading;
namespace Testselenium
{
class Program
{
static void Main(string[] args)
{
var drive3 = new FirefoxDriver();
drive3.Navigate().GoToUrl("http://www.google.com");
IWebElement element21 = drive3.FindElement(By.TagName("body"));
System.Threading.Thread.Sleep(5000);
// element21.Click();
element21.SendKeys(Keys.Control + "t");
// element21.SendKeys(Keys.LeftControl + "t");
//element21.SendKeys(Keys.Control + "T");
IWebDriver driver = new FirefoxDriver();
driver.FindElement(By.CssSelector("body")).SendKeys(Keys.Control + "t");
driver.SwitchTo().Window(driver.WindowHandles.Last());
driver.Navigate().GoToUrl("http://www.google.com");
}
}
}
You can try to open new tab using JavaScriptExecutor:
IJavaScriptExecutor js = (IJavaScriptExecutor)drive3;
js.ExecuteScript("window.open('http://www.google.com');");
This should allow you to open Google main page in new tab. If you want to open empty page - just don't pass arguments to window.open()

Selenium C# Can't find ID or Title

I manage to open a firefox browser, go to http://www.google.com/ search for "Bath Fitter". When i see a bunch of links, i want to in fact click on an item of the top menu provided by Google, Images. Images is located next to Map Videos News...
How can i have it click on Images?
Below is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
namespace SeleniumHelloWorld
{
class Program
{
static void Main(string[] args)
{
IWebDriver driver = null;
try
{
driver = new FirefoxDriver();
driver.Navigate().GoToUrl("http://www.google.com/");
driver.Manage().Window.Maximize();
IWebElement searchInput = driver.FindElement(By.Id("gbqfq"));
searchInput.SendKeys("Bath Fitter");
searchInput.SendKeys(Keys.Enter);
searchInput.FindElement(By.Name("Images"));
searchInput.Click();
driver.Close();
}
catch (Exception e)
{
Console.WriteLine("Exception ****" + e.ToString());
}
}
}
}
More specifically you can also write your selector pointing from Top Navigation. This is the XPath.
.//*[#id='hdtb_msb']//a[.='Images']
try this;
driver.FindElement(By.XPath(".//*[#id='hdtb_msb']//a[.='Images']"));
EDIT:
Even though the selectors above were correct your code was not working because of the second page was taking too long to load. There you need to wait for the the element to be in ready state and an implicit wait is needed. Change the code in your try block and replace with mine and try
driver = new FirefoxDriver();
driver.Navigate().GoToUrl("http://www.google.com/");
driver.Manage().Window.Maximize();
IWebElement searchInput = driver.FindElement(By.Id("gbqfq"));
searchInput.SendKeys("Bath Fitter");
searchInput.SendKeys(Keys.Enter);
//this is the magic
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
By byImage = By.XPath(".//*[#id='top_nav']//a[.='Images']");
IWebElement imagElement =
new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(ExpectedConditions.ElementExists(byImage));
imagElement.Click();
Try something like this...
IList<IWebElement> links = driver.FindElements(By.TagName("a"));
links.First(element => element.Text == "Images").Click();

Categories