Search code examples
javascripthtmlgeolocationweb-worker

Using Geolocation in a HTML5 Web Worker


I want to use a HTML5 web worker to report longitude and latitude to a restful server at regular intervals - even when the tab is not in focus. My problem is that the way that I would normally access the HTML5 geolocation function is not available in the web worker.

What I have tried is sending the geolocation object, from my main file to the web worker. However, that didn't work and I got the following error:

Uncaught DataCloneError: Failed to execute 'postMessage' on 'Worker': An object could not be cloned.

Next I tried importing a JavaScript library which provides geolocation services called Geolocator. But then I found that I do not have access to the library in the worker (I think because the worker doesn't have access to the DOM).

So, in an attempt to combat this, I added the source of this JavaScript library directly into the worker file but this didn't work because I don't have access to window which is used repeated throughout the source of Geolocator.

Is what I am trying to do possible? Is there any alternatives which I can use?


Solution

  • The navigator object in the main thread contains a geolocation property, which is how you access all geolocation functionality.

    Workers contain a different navigator object, known as WorkerNavigator which only contains a subset of the properties of the navigator in the main thread.

    Because the WorkerNavigator lacks a Geolocation object and the Geolocation object can't be serialized into a worker, it appears you can't use Geolocation inside of a web worker. Instead, you'll have to do your reporting from the main thread.