(ws for node.js)
Like this;
socketserver.on('connection', function(socket) {
socket.on('message', function(data) {
// This is in eventone.html on /eventone
if(data == 'eventone') {
console.log("Event one triggered!");
socket.send(foo);
socket.close();
}
// This is in eventtwo.html on /eventtwo
if(data == 'eventtwo') {
console.log("Event two triggered!");
socket.send(bar);
socket.close();
}
// This is in eventthree.html on /eventthree
if(data == 'eventthree') {
console.log("Event three triggered!");
socket.send(foobar);
socket.close();
}
});
});
Is this a good idea for socketing data through one socketserver across different pages?
I want 'foo' to get sent to eventone.html, 'bar' to eventtwo.html and 'foobar' to eventthree.html, which are loaded on the client side, whenever the client sends the respective event through a button press (or whatever).
If this is a good idea, why would you ever use static routing and such things with request and response, why not just send everything through a socket?
Related
so, as you may know there is an admin-ui library (Idk what to call it) in socket.io.
what I want to do is if a client is kicked, send a message to that client (or have the client detect when it is disconnected)
i have tried:
socket.on('disconnect', function(){
alert('disconnected');
});
but that does nothing...
Found a fix using the socket attribute connected and setting an interval to check if the client is connected to a socket:
// client
let offline_alerted = false;
setInterval(function () {
if (socket.connected === false) {
if (offline_alerted === false) {
alert("Disconnected :(");
offline_alerted = true;
}
} else if (offline_alerted === true) {
alert("Reconnected!");
offline_alerted = false;
}
}, 1000);
I might missing something basic, but here is my goal: I have a small instant chat example based on tutorial found here Instant Chat for drupal
The principle is to connect to a nodejs server that basically just broadcast all messages it receives.
I have this function on the client side (inside a drupal tpl.php file):
(function($) {
var myNick = 'me';
var socket = io.connect('http://<?php print $_SERVER['SERVER_ADDR'] ?>:8081');
socket.on('connect', function() {
$('#chat').addClass('connected');
});
socket.on('user message', message);
function message(from, msg) {
if (msg == 'GO') {
** EXECUTE A FUNCTION HERE **
} else { //display the message and sender
$('#lines').append($('<p>').append(from, msg));
}
}
$(document).ready(function() {
$('#send-message').submit(function() {
message(myNick, $('#messageinput').val());
socket.emit('user message', $('#messageinput').val());
clear();
$('#lines').get(0).scrollTop = 10000000;
return false;
});
function clear() {
$('#message').val('').focus();
};
});
})(jQuery);
When I send a message with content =GO, the submit is executed, the message(..,..) function is called and my specific function is executed properly.
But when I receive a GO message, the socket.on event triggers, message() function is called, but my specific function is NOT executed.
Any Idea how I can fix this?
Many thanks for your help.
Michael.
I want to continue to send messages to the content script to run different functions given a URL. Whenever I go to a new URL the messaging stops. How can I make it so the messaging pauses when the new tab URL is loading and then continue on when the tab has loaded?
popup.js
function begin(params) {
chrome.tabs.query({currentWindow: true, active: true}, function(tabs) {
console.log("connecting");
var port = chrome.tabs.connect(tabs[0].id, {name: "testing"});
port.postMessage({test: "test1"});
port.onMessage.addListener(function(msg) {
if (msg.response == "test1 received") {
console.log(msg.response);
port.postMessage({test: "test2"});
} else if (msg.response == "test2 received") {
console.log(msg.response);
port.postMessage({test : "test3"});
} else if (msg.response == "test3 received") {
console.log(msg.response);
port.postMessage({test : "test4"});
}
});
});
}
contentscript.js
chrome.runtime.onConnect.addListener(function(port) {
console.assert(port.name == "testing");
port.onMessage.addListener(function(msg) {
if (msg.test === "test1") {
console.log(msg.test);
// Do stuff and click on new url //
port.postMessage({response: "test1 received"});
} else if (msg.test === "test2") {
console.log(msg.test);
// Do stuff and click on new url //
port.postMessage({response: "test2 recieved"});
});
});
You may need to re-establish the connections, since as per the description of the official guide, a connection is closed in the following situations:
There are no listeners for runtime.onConnect at the other end.
The tab containing the port is unloaded (e.g. if the tab is navigated).
The frame from where connect was called has unloaded.
All frames that received the port (via runtime.onConnect) have unloaded.
runtime.Port.disconnect is called by the other end. Note that if a connect call results in multiple ports at the receiver's end, and disconnect() is called on any of these ports, then the onDisconnect event is only fired at the port of the sender, and not at the other ports.
Here is my background script. I am able to send a message to it from my popup script. In other words, the console logs "hello" in the background page.
// background.js
chrome.runtime.onConnect.addListener(function(port){
port.onMessage.addListener(function(msg) {
if (msg.greeting == "hello") {
var port = chrome.tabs.connect(0, {name: "mycontentscript"});
port.postMessage({greeting:"hello"});
console.log('hello');
}
});
});
However, I cannot get the message from the background script to my content script. Here is my content script. The alert is not showing.
// content.js
var port = chrome.runtime.connect({name:"mycontentscript"});
port.onMessage.addListener(function(message,sender){
if (message.greeting == "hello") {
alert('hello');
}
});
What am I doing wrong? Thanks.
It seems you forgot establishing the connection, just postMessage in content script after the port is created, and reuse the port in runtime.onConnect.addListener() in background page.
background.js
chrome.runtime.onConnect.addListener(function(port) {
port.onMessage.addListener(function(msg) {
if (msg.greeting == "hello") {
port.postMessage({ greeting: "hello" });
console.log('hello');
}
});
});
content.js
var port = chrome.runtime.connect({ name: "mycontentscript" });
port.postMessage({greeting: "hello"});
port.onMessage.addListener(function(message) {
if (message.greeting == "hello") {
alert('hello');
}
});
I don't know if my situation is exactly like yours, but I also wrote a Chrome extension in which the background page sends a message to the client.
In my content script, I do the following:
chrome.runtime.sendMessage('requestData', this.updateData.bind(this));
In my background script, I have:
chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
sendResponse({
messages : inboxMessages,
userId : user_id
});
});
And then my content script receives the message:
this.updateData = function(data) {
//...
}
Hopefully that helps you!
In the background.js:
chrome.runtime.onConnect.addListener(function(port){//here you've got the port
port.onMessage.addListener(function(msg) {
if (msg.greeting == "hello") {
//and here you're making a new, unneeded port, for which nobody is listening.
//Use the one you've got.
var port = chrome.tabs.connect(0, {name: "mycontentscript"});
port.postMessage({greeting:"hello"});
console.log('hello');
}
});
});
Either initiate the connect from background with chrome.tabs.connect, and put chrome.runtime.onConnect listener in the tab's content.js, or initiate the connect from the tab, as you did, and use the port obtained in the background's onConnect listener. Just delete that
var port=chrome.tabs.connect(0, {name: "mycontentscript});
line.
I'm having a tough time getting push notifications (using the ngCordova plugin) to work. I have followed their sample code exactly as is documented on the site: http://ngcordova.com/docs/plugins/pushNotifications/
(the only difference is that I don't have a deviceready listener, instead, my code is inside the ionicPlatform.ready listener.)
Here is my code:
angular.module('myApp', ['ionic', 'ngCordova'])
.run(function($ionicPlatform, $rootScope, $state, $cordovaPush) {
$ionicPlatform.ready(function() {
var config = {
"senderID": "myID100001000"
};
$cordovaPush.register(config).then(function(result) {
alert(result);
}, function(err) {
alert(err);
})
});
$rootScope.$on('$cordovaPush:notificationReceived', function(event, notification) {
switch(notification.event) {
case 'registered':
if (notification.regid.length > 0 ) {
alert('registration ID = ' + notification.regid);
}
break;
default:
alert('An unknown GCM event has occurred');
break;
}
});
})
When my app starts I do get the "OK" alert, so I know it successfully goes through the $cordovaPush.register call. However, I was expecting to get a "registered" notification event, right after, but I never get notified.
Any help would be appreciated.
The solution is in the comments but this needs a proper answer.
First of all, the register callback always returns OK as long as you pass a senderID, but if the $cordovaPush:notificationReceived event is never called (it may take a few seconds), this ID is probably wrong.
You must use the Project Number, not the Project ID.
To get the number, go to the API Console, select the project and you'll be on the Overview page. On top of this page, you'll see something like this:
Project ID: your-project-id Project Number: 0123456789
Just copy and use the project number and everything should work.
I have suffered with this a lot and I have found out, that there are in fact two versions of the cordova push plugin currently:
https://github.com/phonegap-build/PushPlugin (deprecated)
https://github.com/phonegap/phonegap-plugin-push (new one)
Both are supported by ngCordova, but only the deprecated version is documented.
The deprecated version is $cordovaPush
and the newer one is $cordovaPushV5, and they have completely different methods.
For me the problem was that I downloaded the cordova-plugin-push and tried to implement it with the old documentation on ngCordova site.
The code is:
/*
* Non deprecated version of Push notification events
*/
function registerV5() {
$ionicLoading.show({
template: '<ion-spinner></ion-spinner>'
});
if (ionic.Platform.is('browser')) {
alert("You are running on broswer, please switch to your device. Otherwise you won't get notifications");
$ionicLoading.hide();
return;
}
/**
* Configuration doc:
* https://github.com/phonegap/phonegap-plugin-push/blob/master/docs/API.md#pushnotificationinitoptions
*/
var GCM_PROJECT_ID = 'xxxxxx';
$cordovaPushV5.initialize({
"android": {
"clearNotifications": false,
"senderID" : GCM_PROJECT_ID
}
});
$cordovaPushV5.register().then(function (deviceToken) {
console.log("Successfully registered", deviceToken);
$scope.data.deviceToken = deviceToken;
// Below code required to configure $cordovaPushV5 notifications emitter.
// Don't pass function it's not handler.
$cordovaPushV5.onNotification();
$cordovaPushV5.onError();
$ionicLoading.hide();
}, function (error) {
console.log("Failed to registered");
console.log("error object : ", error);
$ionicLoading.hide();
});
}
$rootScope.$on('$cordovaPushV5:notificationReceived', function(event, data) {
console.log("notification received");
console.log("data object: ", data);
var foreground = data.additionalData.foreground || false;
var threadID = data.additionalData.payload.threadID || '';
var group = data.additionalData.payload.group || false;
if (foreground) {
// Do something if the app is in foreground while receiving to push - handle in app push handling
console.log('Receive notification in foreground');
} else {
// Handle push messages while app is in background or not started
console.log('Receive notification in background');
// Open FB messanger app when user clicks notification UI when app is in background.
if (typeof data.additionalData.coldstart != "undefined" && data.additionalData.coldstart == false)
if (!group)
// Open FB Messenger of specific user chat window
window.open('fb-messenger://user/' + threadID, '_system', 'location=no');
else
// Open FB Messenger of specific group chat window
window.open('fb-messenger://groupthreadfbid/' + threadID, '_system', 'location=no');
}
});
$rootScope.$on('$cordovaPushV5:errorOccurred', function(event, error) {
console.log("notification error occured");
console.log("event object: ", event);
console.log("error object: ", error);
});
More on this github article: https://github.com/driftyco/ng-cordova/issues/1125 (code from here) and in this article: https://github.com/yafraorg/yafra/wiki/Blog-Ionic-PushV5