我想在访问网站之前设置我的地理位置。我怎么能这样做?
一个小例子脚本如下:
Capybara.default_driver = :poltergeist
driver_name = "poltergeist_#{rand 1_000_000}"
Capybara.run_server = false
Capybara.current_driver = driver_name
Capybara.default_wait_time = 10
opts = {}
Capybara.register_driver driver_name do |app|
opts = { :js_errors => true, :phantomjs_options => ['--ignore-ssl-errors=yes', '--ssl-protocol=TLSv1'], :timeout => 90 }
Capybara::Poltergeist::Driver.new app, opts
end
user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/537.13+ (KHTML, like Gecko) Version/5.1.7 Safari/534.57.2'
Capybara.current_session.driver.headers = { 'User-Agent' => user_agent}
Capybara
browser = Capybara
# now my attempt to set geolocation, which is unsuccessful.
browser.page.execute_script "navigator.geolocation.getCurrentPosition = function(success, failure) { success({coords: {latitude: 25.455755, longitude: -80.511565}, timestamp: Date.now()}); }"
但如果我现在前往位置感知网站,我不会看到与我的地理位置相关的数据。因此,压倒一切的地理定位失败了。
设置地理位置的正确方法是什么?
答案 0 :(得分:0)
使用execute_script执行此操作将在页面加载后执行(并且通常已经检查过浏览器是否支持地理位置),这使得它无用。相反,你想使用Poltergeist / PhantomJS的扩展能力来模拟地理定位。这是一篇很好的文章,解释了如何执行此操作 - http://collectiveidea.com/blog/archives/2014/01/21/mocking-html5-apis-using-phantomjs-extensions