diff --git a/spec/agent_spec.cr b/spec/agent_spec.cr
index dc46cee..792f2c2 100644
--- a/spec/agent_spec.cr
+++ b/spec/agent_spec.cr
@@ -3,10 +3,21 @@ WebMock.stub(:get, "example.com/")
WebMock.stub(:get, "another_domain.com/")
WebMock.stub(:get, "example.com/cookies1").to_return(headers: {"Set-Cookie" => "id=123"})
WebMock.stub(:get, "example.com/cookies2").to_return(headers: {"Set-Cookie" => "name=kanezoh"})
-WebMock.stub(:get, "html_example.com").to_return(body:
+WebMock.stub(:get, "example.com/meta_cookie").to_return(body:
+<<-BODY
+
+
+ page_title
+
+
+
+
+
+BODY
+)
+WebMock.stub(:get, "html_example.com").to_return(body:
<<-BODY
-
page_title
@@ -55,6 +66,13 @@ describe "Mechanize Agent test" do
agent.request_headers["Cookie"].should eq "id=123; name=kanezoh"
end
+ it "get cookie from meta head" do
+ agent = Mechanize.new
+ agent.get("http://example.com/meta_cookie")
+ agent.get("http://example.com/")
+ agent.request_headers["Cookie"].should eq "id=123"
+ end
+
it "don't send cookies to another domain" do
agent = Mechanize.new
agent.get("http://example.com/cookies1")
diff --git a/src/mechanize/http/agent.cr b/src/mechanize/http/agent.cr
index a007c33..7931a0e 100644
--- a/src/mechanize/http/agent.cr
+++ b/src/mechanize/http/agent.cr
@@ -70,21 +70,19 @@ module MechanizeCr
end
private def add_response_cookies(response, uri, page)
- #if page.body =~ /Set-Cookie/
- # page.css("//head/meta[@http-equiv=\"Set-Cookie\"]").each do |meta|
- # save_cookies(uri, meta["content"])
- # end
- #end
+ if page.body =~ /Set-Cookie/
+ page.css("head meta[http-equiv=\"Set-Cookie\"]").each do |meta|
+ cookie = meta["content"].split(";")[0]
+ key,value = cookie.split("=")
+ cookie = ::HTTP::Cookie.new(name: key, value: value)
+ save_cookies(uri, [cookie])
+ end
+ end
header_cookies = response.try &.cookies
if (header_cookies.nil? || header_cookies.try &.empty?)
return
else
- if cookies.fetch(uri.host.to_s, ::HTTP::Cookies.new).empty?
- cookies[uri.host.to_s] = ::HTTP::Cookies.new
- end
- header_cookies.each do |cookie|
- cookies[uri.host.to_s] << cookie
- end
+ save_cookies(uri, header_cookies)
end
end
@@ -107,6 +105,16 @@ module MechanizeCr
private def reset_request_header_cookies
request_headers.delete("Cookie")
end
+
+ private def save_cookies(uri, header_cookies)
+ host = uri.host.to_s
+ if cookies.fetch(host, ::HTTP::Cookies.new).empty?
+ cookies[host] = ::HTTP::Cookies.new
+ end
+ header_cookies.each do |cookie|
+ cookies[host] << cookie
+ end
+ end
end
end
end