Can we handle browser cookies with Page Object?

Can we process cookies in the browser at runtime?

Actually, I need to get cookies from the browser, and you need to set the modified cookies between script execution. Can we do this with Page Object?

I check the pearl of the page object, we have a gem for clearing cookies, but I need to get and set some cookie values . Any suggestions please ....

+4
source share
2 answers

You will need to interact with the watir-webdriver (or selenium-webdriver) browser directly in order to access the cookie add / delete API.

Assuming you are using watir-webdriver:

page.browser.cookies.clear page.browser.cookies.add 'foo', 'bar' page.browser.cookies.delete 'foo' 

Note that page.browser used to access the base browser of the watir-webdriver browser of the page object.

You can learn more about watir-webdriver cookie API:

If you use selenium-webdriver without watir-webdriver, the API is documented in Selenium :: WebDriver :: Parameters .

+2
source

On any page (class) of a page, you can define a method that processes cookies and accesses them using PageObject. There are several ways to implement a PageObject, depending on what other structures you use, but here is an example of using IRB.

 # Using watir-webdriver class MyPage include PageObject def delete_cookies # Just wrapping this so it convenient in my PageObject @browser.cookies.clear end def get_cookies_as_array # Returns an array of hashes for each cookie @browser.cookies.to_a end def set_browser_cookies( cookie_hash ) # Store the cookie name and value @browser.cookies.add( cookie_hash[:name], cookie_hash[:value] ) end def restore_browser_cookies( cookie_array ) cookie_array.each do | cookie_hash_from_array | self.set_browser_cookies( cookie_hash_from_array ) end end end 

Example IRB:

 >> require "watir-webdriver" >> require "page-object" >> @browser = Watir::Browser.start "http://stackoverflow.com" >> my_page = MyPage.new(@browser) >> @cookies_to_keep = my_page.get_cookies_as_array # Observe the cookies look like this: # [0] # ... # [5] { # :name => "gauthed", # :value => "1", # :path => "/", # :domain => "stackoverflow.com", # :expires => nil, # :secure => false # } # >> my_page.delete_cookies "" # Empty string is returned >> my_page.get_cookies_as_array [] # Empty Array returned because there are no cookies >> my_page.restore_browser_cookies( @cookies_to_keep ) # Cookie array is returned 

The original cookies are restored with their original: name and: value.


The Docs API Justin Ko pointed you to is a very valuable link.

+2
source

Source: https://habr.com/ru/post/1491651/


All Articles