I have problems with simple push on ffos. Here is my code:
var endpoint;
$(document).ready(function() {
registerPush();
navigator.mozSetMessageHandler("push", function(message) {
if(message.pushEndpoint == endpoint) {
console.log("push notification: "+message.version);
}
});
navigator.mozSetMessageHandler("push-register", function() {
registerPush();
});
});
function registerPush() {
var req = navigator.push.register();
req.onsuccess = function(e) {
endpoint = e.target.result;
console.log(endpoint);
}
}
It is working ok when i start the app, but after few minutes if i try to send a push to the endpoint, nothing happens. But when i call the registerPush(); function, everithing works again for few minutes.
It is said that there may be a bug. Some routers may are filtering the push notifications, so that may be the problem. I think It may be bypassed using a 3G connection.
Related
I have been trying to get data chat working using webrtc. It was working previously in google chrome and suddenly stopped working, I have narrowed down the issue to 'ondatachannel' callback function not getting triggered. The exact same code works fine in Mozilla.
Here's the overall code:
app.pc_config =
{'iceServers': [
{'url': 'stun:stun.l.google.com:19302'}
]};
app.pc_constraints = {
'optional': [
/* {'DtlsSrtpKeyAgreement': true},*/
{'RtpDataChannels': true}
]};
var localConnection = null, remoteConnection = null;
try {
localConnection = new app.RTCPeerConnection(app.pc_config, app.pc_constraints);
localConnection.onicecandidate = app.setIceCandidate;
localConnection.onaddstream = app.handleRemoteStreamAdded;
localConnection.onremovestream = app.handleRemoteStreamRemoved;
}
catch (e) {
console.log('Failed to create PeerConnection, exception: ' + e.message);
return;
}
isStarted = true;
In Create Channel that follows this:
var localConnection = app.localConnection;
var sendChannel = null;
try {
sendChannel = localConnection.createDataChannel(app.currentchannel,
{reliable: false});
sendChannel.onopen = app.handleOpenState;
sendChannel.onclose = app.handleCloseState;
sendChannel.onerror = app.handleErrorState;
sendChannel.onmessage = app.handleMessage;
console.log('created send channel');
} catch (e) {
console.log('channel creation failed ' + e.message);
}
if (!app.isInitiator){
localConnection.ondatachannel = app.gotReceiveChannel;
}
app.sendChannel = sendChannel;
I create Offer:
app.localConnection.createOffer(app.gotLocalDescription, app.handleError);
and Answer:
app.localConnection.createAnswer(app.gotLocalDescription, app.handleError);
the offer and answer get created successfully, candidates are exchanged and onicecandidate event is triggered at both ends! Local Description and RemoteDescription are set on both respective ends.
I have a pusher server for signalling, I am able to send and receive messages through the pusher server successfully.
The same webrtc code works for audio/video = true, the only issue is when I try to create datachannel. The only step that does not get executed is the callback function not getting executed i.e "gotReceiveChannel"
I'm starting to think it's the version of chrome.. I am not able to get the GitHub example working in chrome either: (Step4 for data chat)
https://bitbucket.org/webrtc/codelab
While the same code works in Mozilla.
The sendChannel from the offerer has a "readyState" of "connecting"
Any help much appreciated.
I've been implementing a webrtc videochat.
Everything is working smoothly except for the case when the peer closes the browser.
I've been trying to handle this event by implementing an onended callback on the remote mediastream. Though, this callback does not seem to ever be called.
How can I detect that the peer's browser has been closed or that the connection was finished on the other side?
You can use the ICE connection status to determine this. If you disconnect one peer it takes some seconds (~5?) to recoginize it, but it works even without a signalling server.
(assuming you called your peer connection pc)
pc.oniceconnectionstatechange = function() {
if(pc.iceConnectionState == 'disconnected') {
console.log('Disconnected');
}
}
Use signaling gateway to send message to all connected peers that you're leaving; like this:
window.addEventListener('beforeunload', function () {
userLeft();
}, false);
window.addEventListener('keyup', function (e) {
if (e.keyCode == 116)
userLeft();
}, false);
function userLeft() {
signalingGateway.send({
userLeft: true,
whoLeft: 'user-id'
});
}
signalingGateway.on('message', function (signal) {
if (signal.userLeft && signal.whoLeft != 'current-user-id') {
var relevantPeer = listOfPeers[signal.whoLeft];
if (relevantPeer) {
relevantPeer.close();
relevantPeer = null;
}
var relevantLocalStreams = listOfLocalStreams[signal.whoLeft];
if (relevantLocalStreams.length) {
for (var i = 0; i < relevantLocalStreams.length; i++) {
if (relevantLocalStreams[i].stop) {
relevantLocalStreams[i].stop();
}
// it is suggested to stop media tracks instead!
}
}
}
});
I am using a solution like this:
const connection = new RTCPeerConnection(configuration);
connection.onconnectionstatechange = () => {
const connectionStatus = connection.connectionState;
if (["disconnected", "failed", "closed"].includes(connectionStatus)) {
console.log("disconnected");
}
};
I also had this issue. I've solved this by closing the connection at the desired moment(eg. on destructor).
A <- connected -> B
...
Close(A); // after this, B's ice status will go almost instantly to 'kDisconnected'.
Just Use
connection.onclose = function(event){
event.useid // gives the connection closed userid
}
In Firefox 17.0.1 when I try to open the IndexedDB database, Firebug console shows me an InvalidStateError exception. Also request.onerror event is raised, but event.target.errorCode is undefined.
if (window.indexedDB) {
var request = window.indexedDB.open('demo', 1);
request.onsuccess = function(event) {
// not raised
};
request.onupgradeneeded = function(event) {
// not raised
};
request.onerror = function(event) {
// raised with InvalidStateError
};
}
Does anyone have experience with IndexedDB in Firefox?
Update
Firefox 18.0.1 has the same behavior. Comlete source.
I answer because the problem still exists (in Firefox 54). This happens if you:
use Firefox in private mode
or switch between different Firefox versions (https://bugzilla.mozilla.org/show_bug.cgi?id=1236557, https://bugzilla.mozilla.org/show_bug.cgi?id=1331103)
To prevent the InvalidStateError a try catch isn't working (but useful for other errors, e.g. disabled cookies), instead you need event.preventDefault(). Yes I know, too easy to be true. :)
if (window.indexedDB) {
var request = window.indexedDB.open('demo', 1);
request.onsuccess = function(event) {
// not raised
};
request.onupgradeneeded = function(event) {
// not raised
};
request.onerror = function(event) {
// raised with no InvalidStateError
if (request.error && request.error.name === 'InvalidStateError') {
event.preventDefault();
}
};
}
Kudos go to https://bugzilla.mozilla.org/show_bug.cgi?id=1331103#c3.
I am pretty sure the error you get is a version error, meaning the current version of the database is higher then the version you are opening the database with. If you take a look in event.target.error you will see that the name will contain "VersionError".
An other possibility is that you will see "AbortError", that would mean that the VERSION_CHANGE transaction was aborted. Meaning there was an error in the onupgradeneeded event that caused an abort. You could get this if you are creating an object store that already exists.
I see no other possibilities than these too, if not provide some more info about the error you get.
You need to create the object store in a separate transaction, you're lumping both the open database and create object store transaction into the same event.
Also you can't have both autoincrement and a path as options to your object store. You have to pick one or the other.
Here's the code that will get your example going:
function initDB() {
if (window.indexedDB) {
var request = window.indexedDB.open('demo', 1);
request.onsuccess = function(event) {
db = event.target.result;
createObjectStore();
};
request.onupgradeneeded = function(event) {
db = event.target.result;
$('#messages').prepend('blah blah<br/>');
};
request.onerror = function(event) {
$('#messages').prepend('Chyba databáze #' + event.target.errorCode + '<br/>');
};
}
}
function createObjectStore() {
db.close();
var request = window.indexedDB.open('demo', 2);
request.onsuccess = function(event) {
db = event.target.result;
showDB();
};
request.onupgradeneeded = function(event) {
db = event.target.result;
$('#messages').prepend('yeah yeah yeah<br/>');
var store = db.createObjectStore('StoreName', { keyPath: 'id' });
store.createIndex('IndexName', 'id', { unique: true });
};
request.onerror = function(event) {
$('#messages').prepend('Chyba databáze #' + event.target.errorCode + '<br/>');
};
}
If you start getting stuck you can take a look at some indexeddb code I wrote for the Firefox addon-sdk. The code is more complicated than what you need but you'll be able to see all the events, errors, and order of transactions that need to happen. https://github.com/clarkbw/indexed-db-storage
Good luck!
FireFox will also throw an "InvalidStateError" when using IndexedDB, if the browser is set to "Do not store history" in the privacy tab of the FireFox settings.
I believe FireFox basically runs in incognito mode when that setting is set.
IndexedDB is not available when running FireFox in private mode.
Let's suppose I have a View which can make model.fetch() and then a request to the server.
I would like to implement:
1) A checker able to memorise the result
2) refresh the result (making the request to the server) only if the last request to the server is older than ten minutes.
What should I do?
Is there already a piece of code to make that?
define([], function() {
var MyModel = Backbone.Model.extend({
url: function () {
return "http://localhost/restapi/model/";
},
fetch () {
if(diffTime > 10minutes) {
// make request to the server
}
else {
// return memo
}
}
});
});
You need to override the Backbone.sync method http://documentcloud.github.com/backbone/#Sync.
This code does the saving to local storage to implement a cache http://documentcloud.github.com/backbone/docs/backbone-localstorage.html.
It is fairly simple to add some logic in the "read" case to fetch from the server if the data is older than 10 minutes.
As codemonkey said, localstorage would be a good option. But if you don't want to use a library for that, you can use this class to extend those models who require the cache functionality.
var CachedModel = Backbone.Model.extend({
lastFetch: null, // millisec.
cache: { }
fetch: function () {
if(!this.lastFetch || (lastFetch - Date.now() > 10*60*1000) {
// make request to the server
}
else {
// return this.cache
}
}
});
I have found https://github.com/Ask11/backbone.offline to work really well for me.
The only vice is that it uses localStorage, you could also opt for more support by going with rewriting bits and pieces for use with amplify.store http://amplifyjs.com/api/store/.
I'm working on a chat application with Node.js and Socket.io, and on disconnect, the remaining user receives an alert saying that their partner disconnected.
The problem is that every once in a while, Socket.io automatically disconnects then reconnects. My chat application is triggering the alert, even though the partner hasn't really disconnected.
Code:
var clients = {};
var soloClients = [];
io.sockets.on('connection', function (socket) {
//Session start
socket.on('sessionStart', function () {
clients[socket.id] = socket;
soloClients.push(socket.id);
var searchClients = function(){
if(soloClients.length > 1){
var rand = Math.floor(Math.random() * soloClients.length);
if(soloClients[rand] && soloClients[rand] != socket.id){
if(clients[soloClients[rand]]){
var you = clients[socket.id];
var partner = clients[soloClients[rand]]
clients[partner.id]['partner'] = you.id;
clients[you.id]['partner'] = partner.id;
soloClients.splice(soloClients.indexOf(you.id), 1);
soloClients.splice(soloClients.indexOf(partner.id), 1);
partner.emit('partnerConnect', null);
socket.emit('partnerConnect', null);
}
else{
soloClients.splice(rand, 1);
searchClients;
}
}
else{
searchClients();
}
}
};
searchClients();
});
//On disconnect
socket.on('disconnect', function(){
soloClients.splice(soloClients.indexOf(socket.id), 1);
if(clients[socket.id]){
if(clients[clients[socket.id]['partner']]){
clients[clients[socket.id]['partner']].emit('partnerDisconnect', null);
}
delete clients[socket.id];
}
});
});
I was wondering if there is any way to solve this.
Thanks!
Maybe you should try to find out the real reason why the client gets disconnected? I.e. is it a bad connection, or firewall issues, or something else?
Also, you should check the error you get from the disconnect, if it's a clean disconnect (no error) you do the normal notification, but if it's an error you maybe want to handle it differently.
It turns out that this behavior isn't supposed to happen, it was just a bug in that version. This bug has been fixed in the latest version.