diff --git a/CHANGELOG.md b/CHANGELOG.md index 963cf2c8..8d2c9a5d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ - `Ferrum::Browser#close` closes browser gracefully issuing a CDP command, doesn't clean up ruby resources. - `Ferrum::Node#remove` removes node from DOM tree. - `Ferrum::Node#exists?` check whether the node in ruby world still exists in the DOM tree. +- `Ferrum::Cookies#store` stores all cookies of current page in a file. +- `Ferrum::Cookies#load` Loads all cookies from the file and sets them for current page. ### Changed diff --git a/README.md b/README.md index 4140eb3b..893be91d 100644 --- a/README.md +++ b/README.md @@ -882,6 +882,25 @@ Removes all cookies for current page page.cookies.clear # => true ``` +#### store(path) : `Boolean` + +Stores all cookies of current page in a file. + +```ruby +# Cookies are saved into cookies.yml +page.cookies.store # => 15657 +``` + +#### load(path) : `Boolean` + +Loads all cookies from the file and sets them for current page. + +```ruby +# Cookies are loaded from cookies.yml +page.cookies.load # => true +``` + + ## Headers `page.headers` diff --git a/lib/ferrum/cookies.rb b/lib/ferrum/cookies.rb index 46e3d014..0887b2c7 100644 --- a/lib/ferrum/cookies.rb +++ b/lib/ferrum/cookies.rb @@ -1,5 +1,6 @@ # frozen_string_literal: true +require "yaml" require "ferrum/cookies/cookie" module Ferrum @@ -169,6 +170,32 @@ def clear true end + # + # Stores all cookies of current page in a file. + # + # @return [Integer] + # + # @example + # browser.cookies.store # => Integer + # + def store(path = "cookies.yml") + File.write(path, map(&:to_h).to_yaml) + end + + # + # Loads all cookies from the file and sets them for current page. + # + # @return [true] + # + # @example + # browser.cookies.load # => true + # + def load(path = "cookies.yml") + cookies = YAML.load_file(path) + cookies.each { |c| set(c) } + true + end + private def default_domain diff --git a/spec/cookies_spec.rb b/spec/cookies_spec.rb index 8790bd24..a49d9186 100644 --- a/spec/cookies_spec.rb +++ b/spec/cookies_spec.rb @@ -262,4 +262,33 @@ expect(browser.body).to_not include("test_cookie") end end + + describe "#store" do + it "stores cookies" do + page.go_to("/set_cookie") + + page.cookies.store("test.yml") + + cookies = YAML.load_file("test.yml") + expect(cookies.size).to eq(1) + expect(cookies[0]["name"]).to eq("stealth") + expect(cookies[0]["value"]).to eq("test_cookie") + expect(cookies[0]["domain"]).to eq("127.0.0.1") + ensure + File.delete("test.yml") + end + end + + describe "#load" do + it "stores cookies" do + cookie = { "name" => "stealth", "value" => "hello world", "domain" => "127.0.0.1", "path" => "/" } + File.write("test.yml", [cookie].to_yaml) + page.cookies.load("test.yml") + + page.go_to("/get_cookie") + expect(page.body).to include("hello world") + ensure + File.delete("test.yml") + end + end end