user3443200
user3443200

Reputation: 109

fake Geolocation in chrome automation

I need to automate geolocation in chrome using python script. I have to fake the latitude and longitude. I followed some links in stackoverflow but they gave errors. chromeDriver.executeScript("window.navigator.geolocation.getCurrentPosition=function(success){var position = {"coords" : {"latitude": "555","longitude": "999"}};success(position);}");

is there any other way i can change the location?

Upvotes: 4

Views: 7228

Answers (4)

Lelouch
Lelouch

Reputation: 579

Using Python with Selenium 3.141 and ChromeDriver 83.0

This is the working method I found:

params = {
  "latitude": 34.0207305,
  "longitude": -118.6919153,
  "accuracy": 100
}
driver.execute_cdp_cmd("Emulation.clearGeolocationOverride", params)

Upvotes: 3

Dr.BBQ
Dr.BBQ

Reputation: 61

You can use execute_cdp but that is not found in webdriver/remote/remote_connection.py so you could do the following:

chrome_geolocation_format = {
            "location": {
                "latitude": 50.1109,
                "longitude": 8.6821
            }

driver.execute(Command.SET_LOCATION, chrome_geolocation_format)

Upvotes: 0

Dirk N.
Dirk N.

Reputation: 320

It's actually now progammable by using the Chrome Devtools Protocol (cdp):

params = {
    "latitude": 50.1109,
    "longitude": 8.6821,
    "accuracy": 100
}

self.driver = webdriver.Chrome()
self.driver.execute_cdp_cmd("Page.setGeolocationOverride", params)
self.driver.get('https://www.google.com/maps')

Upvotes: 1

srees
srees

Reputation: 296

You have to escape double quotes inside a string please try with below code:

driver.execute_script("window.navigator.geolocation.getCurrentPosition=function(success){"+
                                    "var position = {\"coords\" : {\"latitude\": \"555\",\"longitude\": \"999\"}};"+
                                    "success(position);}");

print(driver.execute_script("var positionStr=\"\";"+
                                "window.navigator.geolocation.getCurrentPosition(function(pos){positionStr=pos.coords.latitude+\":\"+pos.coords.longitude});"+
                                "return positionStr;"))

Upvotes: 1

Related Questions