Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
606 views
in Technique[技术] by (71.8m points)

html - 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 + "
line: " + e.lineno + "
Description: " + 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...