4

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?

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Okay, thats disappointing. Do you know of anything similar to web workers that will run even when a tab isn't in focus?
@Haych I'm not but perhaps you could have a timer running in the web worker then alert the main thread to perform the REST call? I'm not sure if that would work, I haven't tried it.
There is an ongoing discussion on w3c repo that started in September 2015 about possible implementation of Geolocation in ServiceWorkers
0

There is a working example of your proposal that can be found at this question. It currently only works in background on Firefox (for the wrong reasons) and is unlikey to get implemented until we have substantial regime change at W3C/IETF.

But like you, there are many such requirements out there in the real world and I believe my proposal meets most if not all of them.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.