SignalR inside an iframe not receiving - javascript

My web application that utilizes signalR sent from an API hub works well on all browsers. Now, when I try to add the link of my web application inside an iframe within a basic html page, my web application does not execute my connection methods.
Here a snippet of my code in my web application:
$.connection.hub.url = 'myUrl';
$.connection.hub.logging = true;
var varHub= $.connection.MyHub;
$.connection.hub.start()
.done(function () { console.log("Signal R connected"); //this is being executed })
.fail(function () { console.log("Could not Connect to signal R hub!"); });
$.connection.hub.disconnected(function () {
setTimeout(function () {
$.connection.hub.start();
}, 5000); // Re-start connection after 5 seconds
});
//Methods to be called by the server for signal R connections
varHub.client.start= function () {
//this is not being called
//do something
};
As I have said I have no problems when I directly access it via url. The issue only happens when I try to insert the url in an iframe.
Here's how I do it:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<meta http-equiv="X-UA-Compatible" content="IE=11">
</head>
<body width="1280" height="736" style="margin:0;padding:0;overflow:hidden;border:0px;background:#000000;">
<iframe
src="http://myUrl/Home/Index?Id=someId" style="width:1280px;height:720px;margin:0;paddin:0;overflow:hidden;border:0px;"/>
scrolling="no"/>
</body>
</html>
Note: My target browser is IE 11.
Any ideas will be a great help! Thanks.

For anyone who will might encounter this in the future, this parameter fixed my issue.
Source: Here
Negotiating a transport takes a certain amount of time and client/server resources. If the client capabilities are known, then a transport can be specified when the client connection is started. The following code snippet demonstrates starting a connection using the Ajax Long Polling transport, as would be used if it was known that the client did not support any other protocol:
$.connection.hub.start({ transport: 'longPolling' })

Related

Incorporate server socket into an html using Node.js / javascript

I am new to Node.js and javascript, hence don't have much experience and in need of some help.
I have a script that opens a simple server socket and just listens to incoming connection and prints the incoming message to the screen:
var net = require('net');
var server = net.createServer();
server.on('connection', handleConnection);
server.listen(9000, function() {
console.log('server listening to %j', server.address());
});
function handleConnection(conn) {
var remoteAddress = conn.remoteAddress + ':' + conn.remotePort;
console.log('new client connection from %s', remoteAddress);
conn.on('data', onConnData);
conn.once('close', onConnClose);
conn.on('error', onConnError);
function onConnData(d) {
var chunks = [];
chunks.push(d);
console.log('Client at %s says %s', remoteAddress, Buffer.concat(chunks).toString());
conn.write(d);
}
function onConnClose() {
console.log('connection from %s closed', remoteAddress);
}
function onConnError(err) {
console.log('Connection %s error: %s', remoteAddress, err.message);
}
}
I have tested it and it works when i run it from the IDE (eclipse).
What I am trying to do is to incorporate this code inside an HTML file.
The HTML file does not suppose to be accessed from the out side, its for learning purposes only.
Basically i would like to open the HTML file, it should run the code in the background (listen to the socket) and once the is a connection and data coming in it should print it on the screen (sing alert for example).
The HTML code looks like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>some title</title>
</head>
<body>
<script
type = "text/javascript" src = "simple_server.js">
</script>
</body>
</html>
While trying to open the HTML file using a browser or inside eclipse it does nothing.
My question is, is it even possible? If it is, what am i doing wrong and how may I fix it?
Any help would be appreciated. Thank you.

Communicating between browser and local application - Secure connection?

Currently creating an application launcher and updater based on a web page. Knowing the limitations of browsers (security reasons), for my project I needed to have a local application to control the update and the creation of the OS process.
While testing and researching for a good amount of time; Now I have a working local-app, written in Go, that can create a process and kill it from an ajax POST request. I prepared some code to show, how my current attempt looks like (nothing fancy) :
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>api_test</title>
<script src="js/jquery-3.0.0.min.js"></script>
<script src="js/script.js"></script>
</head>
<body>
<h2 id="statusText"></h2>
</body>
</html>
js/script.js
$(document).ready(function(){
console.log("Hey! ;)");
tryConnection();
});
function tryConnection() {
var statusReq = $.ajax({
method: "GET",
url: "http://127.0.0.1:9091/api/test",
dataType: "json"
});
statusReq.fail(function(){
$('#statusText').text("Fail");
setTimeout(tryConnection, 5000);
});
statusReq.done(function(json){
$('#statusText').text(json.status);
console.log("Integer result: " + json.result);
setTimeout(tryConnection, 10000);
});
}
Local application, app.go
package main
import (
"log"
"net/http"
"encoding/json"
)
type APITest struct {
Status string `json:"status"`
Result int `json:"result,omitempty"`
};
func testHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*");
TestValue := APITest{Status: "Works!", Result: 123};
json.NewEncoder(w).Encode(&TestValue);
}
func main() {
log.Println("Started!");
http.HandleFunc("/api/test", testHandler);
err := http.ListenAndServe("127.0.0.1:9091", nil);
if err != nil {
log.Fatal("Error occured:", err);
}
}
Everything seems to be fine! But..
The only problem I currently can't figure out is, How can I actually add support for https:// connections without the need to carry the compiled binary with a cert and key file? Because I want to implement this feature into a https:// only website and mixing together https and http connections, results in a blocked mixed content error from browser security restrictions, which is understandable.
Maybe there are some other ways to implement this kind of communication? (to be clear, for WebSockets a secure connection is needed too).

Immediate Disconnection using websocket in FireFox Addon

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.

Javascript working in Google Chrome but Blocked in IE

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

Running Web Socket Client side programming

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)

Categories