Web Workers 中的 HTML5 navigator.geolocation

2022-01-14 00:00:00 gps geolocation html web-worker

我正在尝试在网络工作者中移动我的 navigator.geolocation 代码.

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

我在 Chrome 和 Safari 上尝试过,但在

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

var isGPSSupported = navigator.geolocation;

var isGPSSupported = navigator.geolocation;

沮丧...他们在规范中说网络工作者应该支持导航器"对象...

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

我的代码如下:

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

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.

推荐答案

我之前也有类似的问题,问过 一个相关问题.现在我相信我已经回答了您的问题(以及我的一个相关问题).

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 只属于主线程中的navigator,不属于工作线程中的navigator.

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

主要原因是即使工作线程中的导航器看起来与主线程中的导航器完全相同,但这两个导航器在 C++ 端具有独立的实现.这就是工作线程不支持 navigator.geolocation 的原因.

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.

相关代码在Navigator.idl 和 WorkerNavigator.idl 在 Chromium 代码中.您可以看到它们是 .idl 文件中的两个独立接口.他们在绑定的 C++ 端有独立的实现.导航器是 DOMWindow,而 WorkerNavigator 是 WorkerGlobalScope.

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.

但是,在 JavaScript 方面,它们具有相同的名称:navigator.由于两个导航器在两个不同的作用域中,所以不存在名称冲突.但是当在 JavaScript 中使用 API 时,如果主线程和工作线程具有相同的名称,人们通常会期望它们具有相似的行为.歧义就是这样发生的.

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.

相关文章