Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 navigator.geolocation in Web Workers

I am trying to move my code for navigator.geolocation in a web worker.

I tried it with Chrome and Safari but getting 'undefined' on

var isGPSSupported = navigator.geolocation;

Frustrated... they said in specification that 'navigator' object should be supported in web workers...

My code is below:

index.js

var gpsWorker = new Worker("app/gpsworker.js");

gpsWorker.onmessage = function (e) {
    alert(e.data);
};

gpsWorker.postMessage("Start GPS!");

gpsWorker.onerror = function (e) {
    alert("Error in file: " + e.filename + "\nline: " + e.lineno + "\nDescription: " + e.message);
};

gpsworker.js

self.onmessage = function (e) {
    initGeoLoc();
}

function initGeoLoc() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function (position) {
            self.postMessage("Got position!");
        });
    } else {
        self.postMessage("GPS is not supported on this platform.");
    }
}

Any hint on what is wrong will be greatly appreciated.

like image 463
Olga Rudchenko Avatar asked Jul 18 '12 03:07

Olga Rudchenko


1 Answers

I had similar question as yours before and asked a related question. Now I believe I have the answer to your question (and also one of my related questions).

navigator.geolocation belongs to navigator in the main thread only, but doesn't belong to navigator in the worker thread.

The main reason is that even though the navigator in worker thread looks exactly the same as the one in main thread, those two navigators have independent implementations on the C++ side. That is why navigator.geolocation is not supported in the worker thread.

The related code is in Navigator.idl and WorkerNavigator.idl in Chromium code. You can see that they are two independent interfaces in the .idl files. And they have independent implementations on the C++ side of the binding. Navigator is an attribute of DOMWindow, while WorkerNavigator is an attribute of WorkerGlobalScope.

However, on the JavaScript side, they have the same name: navigator. Since the two navigators are in two different scopes, there is no name conflict. But when using the APIs in JavaScript, people usually expect similar behavior on both main and worker threads if they have the same name. That's how the ambiguity happens.

like image 141
user1040786 Avatar answered Nov 06 '22 01:11

user1040786