从这篇 Wikipedia 文章看来,方案、主机和端口必须相同才能满足同源策略。
http://en.wikipedia.org/wiki/Same_origin_policy
require 'uri'
class SameOrigin
def self.test(str1, str2)
uri1 = URI.parse(str1)
uri2 = URI.parse(str2)
uri1.scheme == uri2.scheme && uri1.host == uri2.host && uri1.port == uri2.port
end
end
SameOrigin.test "http://google.com", "http://google.com" # => true
SameOrigin.test "http://google.com:80", "http://google.com" # => true
SameOrigin.test "http://google.com", "http://www.google.com" # => false
SameOrigin.test "https://google.com", "http://google.com" # => false
如果您使用Domainatrix库,我发现您可以将代码更改为类似这样的代码来进行测试,但对我来说运行速度有点慢。另一种选择是使用这个 RegEx 来查找 url 的域。RegEx 速度更快,但可能并非在所有情况下都有效。顺便说一句,我在这里找到了 RegEx。
从 ruby 中的字符串中删除子域
require 'rubygems'
require 'domainatrix'
require 'uri'
class SameOrigin
def self.relaxed_test(str1, str2)
d1 = Domainatrix.parse(str1)
d1 = Domainatrix.parse(str2)
uri1 = URI.parse(str1)
uri2 = URI.parse(str2)
uri1.scheme == uri2.scheme &&
d1.domain == d1.domain &&
d1.public_suffix == d1.public_suffix &&
uri1.port == uri2.port
end
def self.relaxed_test2(str1, str2)
uri1 = URI.parse(str1)
uri2 = URI.parse(str2)
re = /^(?:(?>[a-z0-9-]*\.)+?|)([a-z0-9-]+\.(?>[a-z]*(?>\.[a-z]{2})?))$/i
domain1 = uri1.host.gsub(re, '\1').strip
domain2 = uri2.host.gsub(re, '\1').strip
uri1.scheme == uri2.scheme && domain1 == domain2 && uri1.port == uri2.port
end
end
SameOrigin.relaxed_test "http://google.com", "http://google.com" # => true
SameOrigin.relaxed_test "http://google.com:80", "http://google.com" # => true
SameOrigin.relaxed_test "http://google.com", "http://www.google.com" # => false
SameOrigin.relaxed_test "https://google.com", "http://google.com" # => false
SameOrigin.relaxed_test2 "http://google.com", "http://google.com" # => true
SameOrigin.relaxed_test2 "http://google.com:80", "http://google.com" # => true
SameOrigin.relaxed_test2 "http://google.com", "http://www.google.com" # => false
SameOrigin.relaxed_test2 "https://google.com", "http://google.com" # => false