<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
function WebSocketTest()
{
var ws = $.gracefulWebSocket("ws://localhost/Node/");
ws.onopen=function(ev){
alert('Connected to server');
};
ws.send("Client is sending message");
ws.onmessage = function (event) {
var messageFromServer = event.data;
alert('Message' +messageFromServer);
};
ws.onerror=function(ev){
alert('Error' +ev.code);
};
}
<div >
Run WebSocket
</div>
Here I have also added gracefulWebSocket library but Stackoverflow just removed it .I am using chrome browser for this Please help me Thanks in advance
You include js file from there? https://github.com/ffdead/jquery-graceful-websocket
What console tells you? (Developer Tools - F12 key shortcut on Chrome).
Related
I've been working on browser extensions that interact with a local application running a WebSocket server.
Safari and Chrome Extensions were very easy to implement, and after some headache getting a feel for FF development, I thought I would be able to implement WebSockets as I had in the other browsers. However I have had some issues.
I understand that I can't directly create a WebSocket in the "main" js file, and so attempted to use workarounds I found on the internet:
https://github.com/canuckistani/Jetpack-Websocket-Example uses a page-worker as a sort of proxy between main and the WebSocket code. When I implement this code, my WebSocket connection immediately errors w/ {"isTrusted":true} as the only information.
I also tried to use a hiddenframe as it appears this is how 1Password deals with websocket communication in their FF Addon, but this also results in the same immediate error.
When I simply open a websocket connection to my server in my normal FF instance, it connects perfectly, but so far, I haven't gotten anything to work from addon.
making pageWorker with:
var pw = pageWorker.Page({
contentUrl: self.data.url('com.html'),
contentScriptFile: self.data.url('com.js')
})
com.html:
<!DOCTYPE HTML>
<html>
<body>
</body>
</html>
com.js:
document.onready = launchCom();
// Could this need to be on ready?
function launchCom() {
console.log("[com.js] launchCom Called");
var wsAvailable = false;
if ("WebSocket" in window) {
console.log("[com.js] Detected Websocket in Window, attempting to open...");
// WebSocket is supported.
ws = new WebSocket('ws://localhost:9001');
wsAvailable = true;
} else {
console.log("[com.js] Websocket is not supported, upgrade your browser!");
}
}
ws.onmessage = function(event) {
console.log(event.data);
}
ws.onopen = function(evt) {
console.log("[com.js] ws opened. evt: " + evt);
}
ws.onerror = function(evt) {
console.log("[com.js] ws error: " + JSON.stringify(evt));
}
Running this results in:
console.log: xxx: [com.js] launchCom Called
console.log: xxx: [com.js] Detected Websocket in Window, attempting to open...
console.log: xxx: [com.js] ws error: {"isTrusted":true}
console.log: xxx: [com.js] ws closed. evt: {"isTrusted":true}
Any help would be greatly appreciated!
I've solved the problem:
I'm using https://github.com/zwopple/PocketSocket in my OS X application as my server, and there appears to be an issue with PocketSocket and FF.
After changing PocketSocket's PSWebSocketDriver.m line 87 code from
[[headers[#"Connection"] lowercaseString] isEqualToString:#"upgrade"]
to
[[headers[#"Connection"] lowercaseString] containsString:#"upgrade"]
per https://github.com/zwopple/PocketSocket/issues/34,
I was able to open a WebSocket connection from FF addon using the original code, but the server errored on messages.
Setting network.websocket.extensions.permessage-deflate to false in about:config allowed messages to be sent so I added
require("sdk/preferences/service").set("network.websocket.extensions.permessage-deflate", false);
to my main.js and everthing is working!
The tiny change to PocketSocket's code hasn't had any effects on the server interacting with other WebSocket clients.
I also got stuck in similar situation as websocket can't be implemented directly in main.js. I also did the same as you did , may be server is refusing connection. Snippet from my code look like below :
main.js
var wsWorker = require('sdk/page-worker').Page({
contentURL: "./firefoxScript/webSocket.html",
contentScriptFile : ["./firefoxScript/webSocket.js"]
});
webSocket.html
<html>
<head>
<title></title>
</head>
<body>
</body>
</html>
webSocket.js
var ws = new WebSocket('ws://localhost:9451');
ws.onopen = function() {
console.log('Connection open...');
};
ws.onclose = function() {
console.log('Connection closed...');
};
ws.onmessage = function(event) {
console.log('Message recieved...');
};
ws.onerror = function(event) {
console.log('Connection Error...');
};
It's perfectly working fine for me.
Using the code from here for testing. The javascript runs just fine in Google Chrome and Firefox but not in IE.
Ok so it works in IE if I run the html file locally but it does give me a warning at the bottom of the page saying it has disabled some scripts on the page and I have to click it to enable them.(doesnt happen in chrome) but ok I do that and it works. But I then put it on my remote webserver which just hosts the HTML file. The connection is still going to be local to the browser viewing the site. However this wont work in IE but could be because it doesn't even show a warning about the script. The page loads but the js doesn't run.
Im assuming that IE is blocking it by default.
How can I get round this and make it work like it does in chrome. The html/js is below.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script type="text/javascript">
function connect() {
var ws = new WebSocket("ws://localhost:8080/service");
ws.onopen = function () {
alert("About to send data");
ws.send("Hello World"); // I WANT TO SEND THIS MESSAGE TO THE SERVER!!!!!!!!
alert("Message sent!");
};
ws.onmessage = function (evt) {
alert("About to receive data");
var received_msg = evt.data;
alert("Message received = "+received_msg);
};
ws.onclose = function () {
// websocket is closed.
alert("Connection is closed...");
};
};
</script>
</head>
<body style="font-size:xx-large" >
<div>
Click here to start connection</div>
First Open program
</body>
</html>
UPDATE:
Thanks to adam i have checked the f12 Developer console and I get an error:
SCRIPT5022: SecurityError
Thanks to the people that have helped.
The Problem is to do with IE and Edge browser not wanting to connect to "Localhost" however if you change Localhost to 127.0.0.1 it works perfectly.
Updated Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script type="text/javascript">
function connect() {
var ws = new WebSocket("ws://127.0.0.1:8080/service");
ws.onopen = function () {
alert("About to send data");
ws.send("Hello World"); // I WANT TO SEND THIS MESSAGE TO THE SERVER!!!!!!!!
alert("Message sent!");
};
ws.onmessage = function (evt) {
alert("About to receive data");
var received_msg = evt.data;
alert("Message received = "+received_msg);
};
ws.onclose = function () {
// websocket is closed.
alert("Connection is closed...");
};
};
</script>
</head>
<body style="font-size:xx-large" >
<div>
Click here to start connection</div>
First Open program
</body>
</html>
Change
ws://localhost:8080/service
to
ws://{your_remote_domain_host}:8080/service
and it should work
In Firefox (at least), if you hit ESC, then it will close all open WebSockets connections.
I need to capture that disconnection and try to re-connect once it's available again.
Here's an example of the code I've tried to implement, but nothing I can figure out will catch the error and allow me to handle it gracefully.
Have a look at the code: http://jsfiddle.net/w5aAK/
var url = "ws://echo.websocket.org";
try {
socket = window['MozWebSocket'] ? new MozWebSocket(url) : new WebSocket(url);
socket.onopen = function(){
console.log('Socket is now open.');
};
socket.onerror = function (error) {
console.error('There was an un-identified Web Socket error');
};
socket.onmessage = function (message) {
console.info("Message: %o", message.data);
};
} catch (e) {
console.error('Sorry, the web socket at "%s" is un-available', url);
}
setTimeout(function(){
socket.send("Hello World");
}, 1000);
Turn on your console and watch the output.
Am I doing something wrong here, or is it just not possible because the connection is running outside of the scope of the JS script?
Any input would be helpful.
Thanks!
You can attach a handler to the socket.onclose event. It will be called when you hit ESC and the connection is interrupted.
See: http://jsfiddle.net/w5aAK/1/
One problem that you can't get around at the moment is the interrupted error being output to the console. There's no way of capturing that at the moment I'm afraid.
You can't catch it and it's not your fault. It's FireFox bug. Vote for it here:
https://bugzilla.mozilla.org/show_bug.cgi?id=712329
I personally tried all kind of solutions:
event handlers onunload onbeforeunload onclose try..catch some js error handling 3rd party services etc.
You can log to console your socket, it's closed before unload, but FF thinks different.. :(
Solution (not answer directly to the answer, but it works):
It's a bug, so you can't catch, but this info is not Solution. After all kind of crazy workarounds and tries to catch that bug, i finally found this working. If you use socket.io to work with WebScokets it can work with different transport technologies. xhr-polling works with Firefox.
if (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent)) { //test for Firefox/x.x or Firefox x.x (ignoring remaining digits);
socket = io.connect('//' + node_server + '/', {
transports: ['polling']
});
} else {
socket = io.connect('//' + node_server + '/');
}
What helped me - might help you too:
Web Socket support in Node.js/Socket.io for older browser
Define transport types on the client side
socket.io doens't work with transports: [ 'xhr-polling' ]
I just read about web sockets and written this simple client side java script. But it doesn't give me any output even if I run on Chrome browser and I don't know what is the FAULT??
May be google.com doesn't support Web sockets??
<!DOCTYPE html>
<html>
<head>
<title>Web socket Experiment</title>
<script type="text/javascript">
function callWebSocket() {
var socket = new WebSocket("ws://www.google.com");
socket.onopen = function () {
alert("Hello, Connected To WS server");
};
socket.onmessage = function (e) {
alert("The message received is : " + e.data);
};
socket.onerror = function (e) {
alert("An error occured while connecting... " + e.data);
};
socket.onclose = function () {
alert("hello.. The coonection has been clsoed");
};
}
</script>
</head>
<body>
<input type="button" value="Open Connecton" onclcik="callWebSocket()" />
</body>
</html>
Please help..
Thanks
Sneha
you typoed onclcik in your input button. Other than that, your code should work fine, except as minitech mentioned in his comment, I don't think google currently has a web socket script setup for you to use. Try making your own server-side script to point to, or search for an existing 3rd party site example to play with (eg, quick google search and I found ws://echo.websocket.org which i tried your code on and it worked, other than the typo)
When I tried to play around with Web Workers feature in HTML5, my firefox works happily but chrome complains that:
Uncaught TypeError: Cannot call method 'postMessage' of undefined
xstartWorkerworker.html:7 (anonymous function)worker.html:1
onclickworker.html:2
worker.html
<button onclick="xstartWorker()">Start worker</button>
<output id="result"></output>
<script>
function xstartWorker()
{
worker.postMessage({'cmd': 'startWorker', 'msg': 'Start now!'});
}
var worker = new Worker('worker.js');
worker.addEventListener('message', function(e)
{
document.getElementById('result').textContent = e.data;
}
, false);
</script>
worker.js
self.addEventListener('message', function(e)
{
var data = e.data;
switch (data.cmd)
{
case 'startWorker':
self.postMessage('worker thread start now:' + data.msg);
break;
default:
self.postMessage('default');
}
}
, false);
What I can do to make it works in chrome?
BTW, when I tried out the sample at http://playground.html5rocks.com/#inline_workers
and this time chrome works, but firefox complains that
Error: worker is undefined Source File:
http://playground.html5rocks.com/ Line: 39
I'm guessing you're trying to run this on your local machine, not on a webserver. Workers are restricted by the Same Origin Policy, but as the linked Wikipedia page notes,
The behavior of same-origin checks and related mechanisms is not
well-defined in a number of corner cases, such as for protocols that
do not have a clearly defined host name or port associated with their
URLs (file:, data:, etc.).
Loading a local file, even with a relative URL, is the same as loading a file with the file: protocol. So my guess is that the problem is that you're trying to load worker.js as a local file - Chrome doesn't like this (for some good security reasons), though you can force the issue by starting Chrome like this: chrome.exe --allow-file-access-from-files
Alternatively, try serving your script on a local or remote webserver and see if that fixes the problem. (If you have Python installed, you can go to the directory in question and run python -m SimpleHTTPServer 8000, then go to http://localhost:8000/ in your browser).
Chrome can use worker locally without the --allow-file-access-from-files. The worker needs to be loaded as a blob.
Example:
<body>
<button>Start</button>
<div id="output"></div>
<script id="worker_1" type="text/js-worker">
importScripts(base_url + '/worker_lib2.js');
function run(event) {
var msg = event.data;
this.postMessage({ answer: hello(event.data.name)});
}
this.addEventListener('message', run, false);
</script>
<script>
var base_url = window.location.href.replace(/\\/g,'/').replace(/\/[^\/]*$/, '');
var array = ['var base_url = "' + base_url + '";' + $('#worker_1').html()];
var blob = new Blob(array, {type: "text/javascript"});
$('button').click(function() {
var url = window.URL.createObjectURL(blob);
console.log(url);
var worker = new Worker(url);
worker.addEventListener('message', function(event) {
$('#output').html(event.data.answer);
}, false);
worker.postMessage({
name: 'Yannis'
});
});
</script>
</body>
The file worker_lib2.js :
function hello(msg) {
return 'Hello... ' + msg;
}