How can I refresh my Selenium ChromeDriver instance without losing the cookies?

早过忘川 提交于 2019-12-08 13:45:30

I wrote a similar program using java programming language. Please refer the below code. It may be helpful for you. Program has many comments for readability purpose.

public class CookieHandling {
public WebDriver driver;

    @Test
    public void test() throws InterruptedException{
        driver=new FirefoxDriver();
        driver.manage().window().maximize();

        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

        driver.get("http://gmail.com/");
        //Login. So new session created
        driver.findElement(By.id("Email")).sendKeys("email id here");
        driver.findElement(By.id("Email")).sendKeys(Keys.ENTER);
        driver.findElement(By.id("Passwd")).sendKeys("mail password here");
        driver.findElement(By.id("Passwd")).sendKeys(Keys.ENTER);

        //Store all set of cookies into 'allCookies' reference var.
        Set<Cookie> allCookies=driver.manage().getCookies();
        driver.quit();//Quitting the firefox driver
        Thread.sleep(3000);
        //Opening the chrome driver
        System.setProperty("webdriver.chrome.driver","C:\\Users\\kbmst\\Desktop\\temp\\chromedriver.exe");
        //System.setProperty("webdriver.ie.driver","C:\\Users\\kbmst\\Desktop\\temp\\IEDriverServer.exe");
        driver=new ChromeDriver();
        driver.manage().window().maximize();
        //It is very import to open again the same web application to set the cookies.
        driver.get("http://www.gmail.com/");
        //Set all cookies you stored previously
        for(Cookie c:allCookies){
            driver.manage().addCookie(c);
        }
        //Just refresh using navigate()
        driver.navigate().refresh();
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!