How to use Websocket for Firefox Android Addon - javascript

I am trying to write a simple firefox mobile addon that talks with my server side code using Websocket.
I have my code working for Desktop Firefox Addon but I am having difficulty with one for Firefox mobile.
function connectToServer(aWindow) {
var ws = new MozWebSocket("ws://ipaddress:8887"); // LINE 20
// var ws = new WebSocket("ws://ipaddress:8887");
ws.onopen = function() {
showToastMsg(aWindow, 'Sending');
ws.send('data');
}
ws.onmessage = function (evt) {
showToastMsg(aWindow, 'Display')
};
ws.onclose = function() {
};
I have tried both MozWebSocket and WebSocket, but both of them gives me error similar to the following :
E/GeckoConsole(15569): [JavaScript Error: "ReferenceError: MozWebSocket is not defined" {file: "resource://gre/modules/XPIProvider.jsm -> jar:file:///data/data/org.mozilla.firefox/files/mozilla/sq4c77hi.default/extensions/view-source#mydomain.org.xpi!/bootstrap.js" line: 20}]
Anyone know what I need to import or do to be able to reference WebSocket?
I just want to send data back and forth from my Firefox Android addon with my server side code using websocket. Any suggestions?
I am just confused because I have this setup running on Firefox Desktop Addon with very similar code.
Any help would be very appreciated thank you!

Try next solution
var ws = new Services.appShell.hiddenDOMWindow.WebSocket("ws://ipaddress:8887");

Are you using the Add-on SDK? Which file is this code going into?
First off, Mozilla 'un-prefixed' MozWebsocket to Websocket some time ago:
https://www.evernote.com/shard/s1/sh/59230d89-52f6-4f23-81de-75ab88f38c22/f9f1c0c64959ee44bdc833707efe10a9
...however the Websocket api is only available in actually web documents. What I've doen in the past is I've used the page-worker api to load a document in the background and connect to a Websocket server from the worker page:
https://github.com/canuckistani/Jetpack-Websocket-Example
For more in the page-worker api:
https://addons.mozilla.org/en-US/developers/docs/sdk/latest/modules/sdk/page-worker.html
In the future we have plans to expose HTML5 apis more directly to add-on developers.

Related

WebSocket works on HTML file, but fails on hosted web page

I'm trying to use Websocket to remote-control a LG Smart TV (WebOS 4.0) by using JSTVRemote JavaScript library.
It means the LG SmartTV is a websocket server, and my browser is a websocket client. The browser sends commands to control the TV, TV does the job (e.g. Volume Down) and send a response back to the client.
This library uses WebSocket to communicate with TV:
ws = new WebSocket( "wss://192.168.xxx.xxx:3000" ) ;
ws.onopen = function() {
ws.onmessage = function( event ) {
console.log( event ) ;
alert('command successed!')
}
ws.onclose = function() {
logUpdate( "Connection closed." ) ;
}
}
ws.send(someCommand);
When I use it in a local HTML file (open it in browser with file://...), It works correctly. The onmessage event fires and returns the response from TV. Also, the TV does the job of command.
*Chrome, IE and Safari are OK
However, when I use it in a hosted web page (open the same HTML file with http://... or https://...), the onmessage event does not file and it reports an error with "WebSocket is already in CLOSING or CLOSED state.". Of course, the TV does not do the job of command.
*the connection establishing seems to succeed because the new WebSocket(), ws.onopen() and ws.send() are OK.
I have tried following web server, but they don't work.
Apache
IIS
Web Server of QNAP(a NAS Server)
Does anyone know the reason of it?

Websocket not connecting to openfire using firefox

I have the following script through which I am trying to connect to openfire using WebSocket built in Firefox.
index.js
console.log(window.WebSocket);
var exampleSocket = new WebSocket("ws://localhost:5222/")
but it shows me the following error on browser console.
Firefox can’t establish a connection to the server at
ws://localhost:5222/.
can anybody tell me what I am doing wrong or there any other better way of doing this. I am using the latest version of Firefox.
First of all, make sure you have installed Openfire WebSocket plugin in the Openfire. so first check it's availability in plugins available. and then write the code as follows.
var exampleSocket = new WebSocket("ws://localhost:7070/ws/",'xmpp')
XMPP is the protocol for openfire
in case you want to check for the error you have to do like this.
exampleSocket.onerror = function(data){
console.log(data);
}

WebSocket to localhost not working on Microsoft Edge

I've created a simple WebSocket server and am trying to connect to it with the following code:
function test(name) {
var ws = new WebSocket('ws://localhost:1234');
ws.onopen = function () {
ws.send('Hello from ' + name);
}
}
test('Edge');
This works fine from Chrome and IE11 on Windows10 but when I try from Edge, the onopen function isn't called, instead I eventually get the following error:
SCRIPT12029: WebSocket Error: Network Error 12029, A connection with the server could not be established
This is happening for version 12.10240 of Edge.
A similar problem was asked about here but the error message is different.
Things I tried:
IP - localhost, 127.0.0.1, the actual IP
Allow localhost loopback flag - both on and off
When trying to communicate with a different machine the problem does not occur.
Is this a defect in Edge or am I doing something wrong?
I had a similar problem, but it was when actually navigating to pages in the browser. I could use the phrase localhost and it worked fine, but I didn't work when I used my machine's name. I found this forum where they suggested that you run the following command in a administrator prompt:
CheckNetIsolation LoopbackExempt -a -n=Microsoft.MicrosoftEdge_8wekyb3d8bbwe
Worked for me. Thought you might be seeing some form of the same issue.
As the forum suggests, you can now also do this by opening Edge and navigating to "about:flags", then tick "Allow localhost loopback (this might put your device at risk)" under "Developer Settings". Should feel a little safer than pasting random stuff into your command prompt.
Edit: As tresf pointed out below, the loopback checkbox in the about:flags appears to have stopped working (as a fix), so you'll have use the CheckNetIsolation command, to make Edge exempt.

WebSocket onmessage() not being called when messages are sent

I'm using autobahn 0.4.10 (https://github.com/oberstet/Autobahn) as a WebSocket server to send messages to a Google Chrome Extension. I am able to open and close connections using WebSocket(), but when I call autobahn.websocket.WebSocketServerProtocol.sendMessage() the message appears to be sent but isn't delivered until the connection is closed.
The api for WebSocketServerProtocol's sendMessage() (derived from WebSocketProtocol) can be found here: http://www.tavendo.de/autobahn/doc/python/websocketprotocol.html#autobahn.websocket.WebSocketProtocol
Has anyone experienced this problem before?
The code I have been on the client side is (js):
ws = new WebSocket('ws://localhost:4444');
ws.onmessage = function(event) {
console.log('hii');
}
And on the server (python)...
#json is a string object
def sendEvent(self, json):
print 'to', self.peerstr
self.sendMessage(json, sync=True)
Both Autobahn and my version of Chrome (17.0.963.46) appear (from what I've gotten out of the headers and docs) to use version 13 of the WebSocket draft protocol.
Turns out this was a threading problem with some threads block the twisted reactor.
See:
http://groups.google.com/group/autobahnws/browse_thread/thread/6bf0c43ec169efc3#
http://twistedmatrix.com/documents/current/core/howto/threading.html
Autobahn works with Chrome (tested up to v19 .. Canary).
Could you try the
https://github.com/oberstet/Autobahn/blob/master/demo/broadcast/broadcast_server.py
demo to see if you have a general issue?
If that runs, direct your extension to that demo server .. it'll send you 1 tick per sec.
You can also enable debug output by changing the factory line to code like this
https://github.com/oberstet/Autobahn/blob/master/demo/echo/echo_server_with_logging.py#L50
2 more notes:
you don't need the sync = True option (it's really an advanced option .. mostly used with the Autobahn WS testsuite)
you might wanna join http://groups.google.com/group/autobahnws .. get answers more quickly .. I discovered your Q only by accident here
Disclosure: I am author of Autobahn and work for Tavendo.

.Net WebSocket Prototype...Trouble Opening Connection in Javascript

Hi I have a Web Application and a Console Application in my C# .Net solution. I am trying to call a ReverseService class in my Console Application from my Web Application. In the Console Application in the static void Main function I am running the following code:
var host = new WebSocketsHost<ReverseService>(new Uri("ws://localhost:4502/reverse"));
host.AddWebSocketsEndpoint();
host.Open();
Console.ReadLine();
I am trying to call this WebSocketEndpoint from my Web Application with the following Javascript code in Chrome 12.
if (window.WebSocket) {
//establishes websocket connection
websocket = new WebSocket('ws://localhost:4502/reverse');
websocket.onopen = function () {
$('body').append('Connected.');
$('#inputbox').keyup(function () {
websocket.send($('#inputbox').val());
});
};
websocket.onclose = function () {
$('body').append('Closed.');
}
websocket.onmessage = function (event) {
$('#outputbox').val(event.data);
};
}
The websocket.onclose function does in fact get called, but the websocket.onopen function never does. I've googled and looked on here but to no avail, any help would be greatly appreciated.
The error is almost certainly a mismatch between the protocol versions for your client and server. It looks like you are using the HTML5 labs prototype - if you are using the most recent version then your server is talking WebSockets hybi-09. Chrome implements a much older version of the protocol (I think its hixie-76 but I am not certain).
Your options are:
Use a WebSocket server that implements hixie-76
Use a different client implementation. For example, you could use the implementation that is provided with the HTML5 labs prototype. Its a Silverlight plugin with a JavaScript wrapper. You need to include a few scripts and use new WebSocketDraft instead of new WebSocket. You will also need to drop the clientaccesspolicy.xml file in your wwwroot - see the prototype readme file for more info. Have a look at some of the samples for more info.
Use a TCP packet sniffer to watch the protocol handshake.
Successful tests with two protocols :
hybi-00/hixie-76 : Firefox 5.0, Safari 5.1.1 use this old protocol with Sec-WebSocket-Key1/Key2...
There are several free server source codes in C#.
For example search WebSocket76English.zip. It works even with Safari on iPhone.
hybi-06 : Firefox 7.0, Chrome 14 are using the last protocol with Sec-WebSocket-Key.
The last .Net WebSocket prototype use that protocol.
If someone has a version of WebSocket prototype supporting the old protocol hybi-00, please let me know.
The last specification draft suggest that a server can support several protocols and tell about
the supported versions in field Sec-WebSocket-Version.

Categories

Resources