How to enable cookie in phantomjsdriver selenium c#?


We can enable cookie with Selenium Webdriver in C#. A cookie is the data stored by the browser. A key−value pair is used to store the information in cookies to hold the relevant information.

To add a cookie, the method AddCookie is used. The key and value of the cookie are passed as parameters to the method. Also, to obtain the cookie information, GetCookieNamed method is used.

Syntax

driver.Manage().Cookies.AddCookie(new Cookie("Automation", "QA"));
driver.Manage().Cookies.GetCookieNamed("Automation");

For implementation we shall be using the NUnit framework.

Example

using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using System;
namespace NUnitTestProject1{
   public class Tests{
      String u = "https://www.tutorialspoint.com/index.htm";
      IWebDriver d;
      [SetUp]
      public void Setup(){
         //creating object of FirefoxDriver
         d = new FirefoxDriver();
      }
      [Test]
      public void Test1(){
         //launching URL
         d.Navigate().GoToUrl(u);
         //adding cookie
         d.Manage().Cookies.AddCookie(new Cookie("Automation", "QA"));
         //obtain cookie
         var c = d.Manage().Cookies.GetCookieNamed("Automation");
         Console.WriteLine(c);
      }
      [TearDown]
      public void close_Browser(){
         d.Quit();
      }
   }
}

Output

Click on Run All Tests button −

Click on Open additional output for this result link −

We should get the Test Outcome and Standard Output.

Updated on: 30-Jan-2021

141 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements