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.
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.
The 'navigator' object is supported, however it only contains four properties: appName, appVersion, userAgent, and platform.
From looking at your code, it appears you are trying to track the user's location as it changes. You do not have to use web workers to accomplish this. You can simply monitor the user's location on the main thread using watchPosition(), which will automatically notify a callback function whenever the user's location changes:
navigator.geolocation.watchPosition(function(position) {
document.getElementById('currentLat').innerHTML = position.coords.latitude;
document.getElementById('currentLon').innerHTML = position.coords.longitude;
});
Inspecting it in chrome, it appears it definitely doesn't have the geolocation attribute:
WorkerNavigator
appName: "Netscape"
appVersion: "5.0 (Windows NT 6.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1"
onLine: true
platform: "Win32"
userAgent: "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1"
__proto__: WorkerNavigator
In Chrome, you can set a breakpoint in your workers. I'd recommend doing this for your errors, its extremely helpful.
Would it not suffice to have the watchPosition(success) in the main-thread postMessage() the new location to your webWorker?
Related
The script below works fine in FireFox and Chrome, but in Internet Explorer 11, it always fails (with POSITION_UNAVAILABLE).
I have set the browser to allow requests for position, and I agree to the prompt the browser presents me when requesting permission.
I'm almost certain that this worked fine a few months ago when I was last experimenting with it. What could I be missing as far as IE's settings?
<script type="text/javascript">
$(document).ready(function () {
if (Modernizr.geolocation)
{
navigator.geolocation.getCurrentPosition(positionSuccess, positionError, { enableHighAccuracy: true, maximumAge: 60000, timeout: 10000 })
}
else
{
$("#GeoError").html("Unable to retrieve current position.")
}
});
function positionSuccess(position)
{
$("#Latitude").val(position.coords.latitude);
$("#Longitude").val(position.coords.longitude);
}
function positionError(error)
{
var message = "";
// Check for known errors
switch (error.code) {
case error.PERMISSION_DENIED:
message = "This website does not have your permission to use the Geolocation API";
break;
case error.POSITION_UNAVAILABLE:
message = "Your current position could not be determined.";
break;
case error.PERMISSION_DENIED_TIMEOUT:
message = "Your current position could not be determined within the specified timeout period.";
break;
}
// If it's an unknown error, build a message that includes
// information that helps identify the situation, so that
// the error handler can be updated.
if (message == "") {
var strErrorCode = error.code.toString();
message = "Your position could not be determined due to " +
"an unknown error (Code: " + strErrorCode + ").";
}
$("#GeoError").html(message)
}
</script>
Also, I get the same failure in IE11 when I try http://html5demos.com/geo, where both FireFox and Chrome work fine.
Does you enable the Location Service?
I have had the same issue, it worked after I enabled the Location Service in my windows 2016.
This page shows how to enable the Location Service in windows 10.
I have had the same issue in IE11 only.
I had to set enableHighAccuracy to false to get it to work. Once I did that IE worked as expected.
In Internet Options, click on the Privacy tab. Uncheck the Never allow websites to request your physical location box, hit on OK.
After making these changes, the http://html5demos.com/geo now worked for me. Initially it didn't.
aha, just discovered something.
Chrome apparently uses the WIFI access points to help finding the location.
IE11 (and edge) just falls back to the default location in your windows settings, if there is no immediate GPS signal.
I have created two Chrome apps and I want to pass some data (string format) from one Chrome app to another Chrome app. Appreciate if someone can help me with showing the correct way of doing this?
It's an RTFM question.
From Messaging documentation (note that it mentions extensions, but it works for apps):
In addition to sending messages between different components in your extension, you can use the messaging API to communicate with other extensions. This lets you expose a public API that other extensions can take advantage of.
You need to send messages using chrome.runtime.sendMessage (using app ID) and receive them using chrome.runtime.onMessageExternal event. If required, long-lived connections can also be established.
// App 1
var app2id = "abcdefghijklmnoabcdefhijklmnoab2";
chrome.runtime.onMessageExternal.addListener(
// This should fire even if the app is not running, as long as it is
// included in the event page (background script)
function(request, sender, sendResponse) {
if(sender.id == app2id && request.data) {
// Use data passed
// Pass an answer with sendResponse() if needed
}
}
);
// App 2
var app1id = "abcdefghijklmnoabcdefhijklmnoab1";
chrome.runtime.sendMessage(app1id, {data: /* some data */},
function(response) {
if(response) {
// Installed and responded
} else {
// Could not connect; not installed
// Maybe inspect chrome.runtime.lastError
}
}
);
Is it possible to use the bluetooth javascript extension API to implement a bluetooth server (in other words, listen on a socket) which can allow a device (bluetooth client) to connect?
According to current documentation and the very few examples, I found it unclear if this is a possibility.
Thanks.
Yes: https://developer.chrome.com/apps/app_bluetooth#listening
var uuid = '1105';
chrome.bluetoothSocket.create(function(createInfo) {
chrome.bluetoothSocket.onAccept.addListener(function(acceptInfo) {
if (info.socketId != createInfo.socketId) return;
// Say hello...
chrome.bluetoothSocket.send(acceptInfo.clientSocketId,
data, onSendCallback);
// Accepted sockets are initially paused,
// set the onReceive listener first.
chrome.bluetoothSocket.onReceive.addListener(onReceive);
chrome.bluetoothSocket.setPaused(acceptInfo.clientSocketId, false);
});
chrome.bluetoothSocket.listenUsingRfcomm(
createInfo.socketId, uuid, function() {
// check chrome.runtime.lastError
});
});
I am developing a Chrome Extesion for the first time and I am following the only guide that explains something about that: HTML5 ROCKS - FILESYSTEM.
I need to get storage for my extension and I resolved so:
window.webkitStorageInfo.requestQuota(window.PERSISTENT,1024*1024, onInitFs, errorHandler);
Ok, it works.
Now I need to create a xml file into the root, but in "onInitFs" the "fs" var is only a number and "fs.root" can't get it.
function onInitFs(fs){
console.log(fs.root); // -> Undefined
fs.root.getFile('list.xml', {create: true, exclusive: true}, function(fileEntry) {
fileEntry.isFile === true;
fileEntry.name == 'list.xml';
fileEntry.fullPath == '/list.xml';
}, errorHandler);
}
Can anybody explain why it doesn't work and how to resolve this issue?
Using RequestFileSystem within Chrome Extension
In order to use the FileSystem API as a root filesystem for your Chrome extension, you can actually use window.webkitRequestFileSystem instead of requestQuota.
window.webkitRequestFileSystem(window.PERSISTENT, 1024 * 1024, function (filesystem) {
console.log(filesystem);
console.log(filesystem.root);
}, function (e) { console.log("Could not request File System"); });
This does print correctly on Chrome 15,16 and 17 for me:
DOMFileSystem
DirectoryEntry
Using requestQuota for HTML5 apps
Just for reference, this would be the way to actually request the quota (i.e., when not using a Chrome Extension). You have to request the quota (the user sees a little banner at the top of his/her window) first. The RequestFileSystem is called if the user accepts.
window.webkitStorageInfo.requestQuota(PERSISTENT, 1024*1024, function(grantedBytes) {
window.webkitRequestFileSystem(PERSISTENT, grantedBytes, onInitFs, errorHandler);
}, function(e) {
console.log('Error requesting filesystem', e);
});
Eventually it might be necessary to request quota within an extension. Currently this can be circumvented with the unlimitedStorage permission. For the current state of implementation/storage types, see http://code.google.com/chrome/whitepapers/storage.html
Until current stable version 17.x, you cannot use HTML5 FileSystem API in Chrome extension. I have try this, the browser will crash down if I call FileSystem API in background page.
And here is a HTML5 API list what you can use in Chrome extension:
http://code.google.com/chrome/extensions/api_other.html
Is it possible to modify the user agent from within a chrome extension?
I am developing an extension for web developers (yes I'm aware of Chromes own extension for this).
Any ideas?
Example code changing the User-Agent for an Android one.
var MOBILE_CHROME_USER_AGENT = 'Mozilla/5.0 (Linux; U; Android-4.0.3; en-us; Galaxy Nexus Build/IML74K) AppleWebKit/535.7 (KHTML, like Gecko) CrMo/16.0.912.75 Mobile Safari/535.7';
chrome.webRequest.onBeforeSendHeaders.addListener(
function(details) {
for (var i = 0; i < details.requestHeaders.length; ++i) {
if (details.requestHeaders[i].name === 'User-Agent') {
details.requestHeaders[i].value = MOBILE_CHROME_USER_AGENT;
break;
}
}
return {requestHeaders: details.requestHeaders};
}, {urls: ['<all_urls>']}, ['blocking', 'requestHeaders']);
The WebRequest API is no longer experimental; You can read all about it at its new home:
chrome.webRequest
and yes you can use it to alter the User-Agent header.
There's experimental WebRequest API for these purposes. You can prevent URL requests, change request headers etc. Of course you can't yet upload your extension to Chrome Web Store if your code uses experimental features of Chrome extensions.