Exception doing StreamHub Hello World example: Invalid url for WebSocket ws://localhost:7878ws/ - comet

I'm running through the StreamHub hello world example from the online article Getting Started with Reverse Ajax and Comet. I think I've configured everything exactly as the article instructs, but I'm getting a JavaScript exception at new StreamHub().connect(..)
Here's my HTML file:
<html>
<head>
<title>Hello World Comet Application</title>
<script type="text/javascript" src="streamhub-min.js"></script>
</head>
<body>
<h1>Hello World Comet Application</h1>
<input type="button" value="say hello" onclick="start()">
<div id="streamingData"></div>
<script>
function topicUpdated(sTopic, oData) {
var newDiv = document.createElement("DIV");
newDiv.innerHTML = "Update for topic '" + sTopic
+ "' Response: '" + oData.Response + "'";
document.getElementById("streamingData").appendChild(newDiv);
}
function start() {
var hub = new StreamHub();
hub.connect("http://localhost:7878/");
hub.subscribe("HelloWorld", topicUpdated);
}
</script>
</body>
</html>
The line where the exception is being thrown is:
hub.connect("http://localhost:7878/");
It happens each time I click the "say hello" button, and the exception I'm getting is:
Invalid url for WebSocket ws://localhost:7878ws/
My browser is Chrome 11.0.696.28 beta, but I'm also having a similar problem on IE7, so I don't think it's browser-related. It's kind of strange URI, isn't it? ws://localhost:7878ws/
What am I doing wrong?

I got the answer on the StreamHub blog. Apparently the tutorial in their earlier blog post is out of date. Here's what needs to be done:
If you migrate any existing Ajax SDK apps from 2.0.x to 2.1 or 2.2 you will need to change your connection URLs to incorporate the new streamhub context. For example, if previously you were using:
hub.connect("http://localhost:7979/");
You will now need to use:"
hub.connect("http://localhost:7979/streamhub/");
After changing the connection string, everything worked just fine.

Related

My HTML + JavaScript code works on online editors, but not offline

I'm working with Sheets, for converting google sheets into JSON files, and then with their API transform the JSON into javascript objects.
The problem is that the code works just fine in online editors just like Tryit from W3Schools or Codepen, but if I put it in an HTML file and open it with Chrome or Edge, it won't work. Does anyone know why? Will it work if I mount the site online?
<head>
<!-- Add Sheetsu Web Client script to the head -->
<script src="//script.sheetsu.com/"></script>
</head>
<body>
<div id="list"></div>
<script>
// API returns array of objects
// Iterate over them and add each element as a list element
function successFunc(data) {
data.forEach(function(item, i) {
document.getElementById("list").innerHTML += "<li>" + item.Precio + " " + item.Tipo + "</li>";
});
}
function errorFunc(e) {
console.log(e);
}
Sheetsu.read("https://sheetsu.com/apis/v1.0su/110ccf6a6812", {}).then(successFunc, errorFunc);
</script>
</body>
Thanks in advance
The problem is this:
<script src="//script.sheetsu.com/"></script>
When you start a resource/asset URL with "//" and without a protocol (http|https), it matches the protocol of where the page is loading. If you are opening a local html file directly, that protocol becomes file://, so the requested URL ends up being file://script.sheetsu.com/, which of course does not exist.
Change it to:
<script src="https://script.sheetsu.com/"></script>
I have tried Firefox and it worked. Check the image below:

not well-formed Source File in mozilla firefox

Following is the content of my JSON File -
{
"tags": [
"Red",
"Green",
"Blue",
"Yellow"
]
}
I checked this with jsonlint but still I am getting the following error in firefox.
Timestamp: Wednesday 18 June 2014 10:39:41 IST Error: not well-formed
Source File:
file:///home/trialcode/trialcode/Projects/ang/18-06-2014/ang/content.json
Line: 1, Column: 1 Source Code: {
I am not sure what I am doing wrong if any.
FYI -
OS - Linux Ubuntu 12.04
Firefox - 24.0
EDIT
I am using the content of content.json file in angular controller via $http.get method.
I explored more about this kind of error and found it is related with the Content-Type setting.
Following is the full code -
<!doctype html>
<html lang="en" ng-app="app">
<head>
<title>JSON Read In Angularjs</title>
<meta charset="UTF-8" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js"></script>
<script>
var app = angular.module('app', []);
app.controller('myCtrl', function($scope, $http){
$scope.data = {};
$http.get('content.json').success(function(data) {
$scope.data = data;
});
});
</script>
</head>
<body ng-controller="myCtrl">
<ul>
<li ng-repeat="em in data.tags">{{em}}</li>
</ul>
</body>
</html>
How do I set the content type if that is a problem. I searched HERE but unable to fix it. Help me Please if any.
After few hours of searching I came across that -
Chrome and other modern browsers have implemented security
restrictions for Cross Origin Requests, which means that you cannot
load anything through file:/// , you need to use http:// protocol at
all times, even locally -due Same Origin policies.
Source -
Cross Origin Script Stackoverflow Answer
Simple Solution For Local Cross Origin Requests

Is cross-origin postMessage broken in IE10?

I'm trying to make a trivial postMessage example work...
in IE10
between windows/tabs (vs. iframes)
across origins
Remove any one of these conditions, and things work fine :-)
But as far as I can tell, between-window postMessage only appears to work in IE10 when both windows share an origin. (Well, in fact -- and weirdly -- the behavior is slightly more permissive than that: two different origins that share a host seem to work, too).
Is this a documented bug? Any workarounds or other advice?
(Note: This question touches on the issues, but its answer is about IE8 and IE9 -- not 10)
More details + example...
launcher page demo
<!DOCTYPE html>
<html>
<script>
window.addEventListener("message", function(e){
console.log("Received message: ", e);
}, false);
</script>
<button onclick="window.open('http://jsbin.com/ameguj/1');">
Open new window
</button>
</html>
launched page demo
<!DOCTYPE html>
<html>
<script>
window.opener.postMessage("Ahoy!", "*");
</script>
</html>
This works at: http://jsbin.com/ahuzir/1 -- because both pages are hosted at the same origin (jsbin.com). But move the second page anywhere else, and it fails in IE10.
I was mistaken when I originally posted this answer: it doesn't actually work in IE10. Apparently people have found this useful for other reasons so I'm leaving it up for posterity. Original answer below:
Worth noting: the link in that answer you linked to states that postMessage isn't cross origin for separate windows in IE8 and IE9 -- however, it was also written in 2009, before IE10 came around. So I wouldn't take that as an indication that it's fixed in IE10.
As for postMessage itself, http://caniuse.com/#feat=x-doc-messaging notably indicates that it's still broken in IE10, which seems to match up with your demo. The caniuse page links to this article, which contains a very relevant quote:
Internet Explorer 8+ partially supports cross-document messaging: it
currently works with iframes, but not new windows. Internet Explorer
10, however, will support MessageChannel. Firefox currently supports
cross-document messaging, but not MessageChannel.
So your best bet is probably to have a MessageChannel based codepath, and fallback to postMessage if that doesn't exist. It won't get you IE8/IE9 support, but at least it'll work with IE10.
Docs on MessageChannel: http://msdn.microsoft.com/en-us/library/windows/apps/hh441303.aspx
Create a proxy page on the same host as launcher. Proxy page has an iframe with source set to remote page. Cross-origin postMessage will now work in IE10 like so:
Remote page uses window.parent.postMessage to pass data to proxy page. As this uses iframes, it's supported by IE10
Proxy page uses window.opener.postMessage to pass data back to launcher page. As this is on same domain - there are no cross-origin issues. It can also directly call global methods on the launcher page if you don't want to use postMessage - eg. window.opener.someMethod(data)
Sample (all URLs are fictitous)
Launcher page at http://example.com/launcher.htm
<!DOCTYPE html>
<html>
<head>
<title>Test launcher page</title>
<link rel="stylesheet" href="/css/style.css" />
</head>
<body>
<script>
function log(msg) {
if (!msg) return;
var logger = document.getElementById('logger');
logger.value += msg + '\r\n';
}
function toJson(obj) {
return JSON.stringify(obj, null, 2);
}
function openProxy() {
var url = 'proxy.htm';
window.open(url, 'wdwProxy', 'location=no');
log('Open proxy: ' + url);
}
window.addEventListener('message', function(e) {
log('Received message: ' + toJson(e.data));
}, false);
</script>
<button onclick="openProxy();">Open remote</button> <br/>
<textarea cols="150" rows="20" id="logger"></textarea>
</body>
</html>
Proxy page at http://example.com/proxy.htm
<!DOCTYPE html>
<html>
<head>
<title>Proxy page</title>
<link rel="stylesheet" href="/css/style.css" />
</head>
<body>
<script>
function toJson(obj) {
return JSON.stringify(obj, null, 2);
}
window.addEventListener('message', function(e) {
console.log('Received message: ' + toJson(e.data));
window.opener.postMessage(e.data, '*');
window.close(self);
}, false);
</script>
<iframe src="http://example.net/remote.htm" frameborder="0" height="300" width="500" marginheight="0" marginwidth="0" scrolling="auto"></iframe>
</body>
</html>
Remote page at http://example.net/remote.htm
<!DOCTYPE html>
<html>
<head>
<title>Remote page</title>
<link rel="stylesheet" href="/css/style.css" />
</head>
<body>
<script>
function remoteSubmit() {
var data = {
message: document.getElementById('msg').value
};
window.parent.postMessage(data, '*');
}
</script>
<h2>Remote page</h2>
<input type="text" id="msg" placeholder="Type a message" /><button onclick="remoteSubmit();">Close</button>
</body>
</html>
== WORKING SOLUTION IN 2020 without iframe ==
Building on answer by tangle, I had success in IE11 [and emulated IE10 mode] using following snippet:
var submitWindow = window.open("/", "processingWindow");
submitWindow.location.href = 'about:blank';
submitWindow.location.href = 'remotePage to communicate with';
Then I was able to communicate using typical postMessage stack, I'm using one global static messenger in my scenario (although I don't suppose it's of any significance, I'm also attaching my messenger class)
var messagingProvider = {
_initialized: false,
_currentHandler: null,
_init: function () {
var self = this;
this._initialized = true;
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
eventer(messageEvent, function (e) {
var callback = self._currentHandler;
if (callback != null) {
var key = e.message ? "message" : "data";
var data = e[key];
callback(data);
}
}, false);
},
post: function (target, message) {
target.postMessage(message, '*');
},
setListener: function (callback) {
if (!this._initialized) {
this._init();
}
this._currentHandler = callback;
}
}
No matter how hard I tried, I wasn't able to make things work on IE9 and IE8
My config where it's working:
IE version: 11.0.10240.16590, Update versions: 11.0.25 (KB3100773)
Building upon the answers by LyphTEC and Akrikos, another work-around is to create an <iframe> within a blank popup window, which avoids the need for a separate proxy page, since the blank popup has the same origin as its opener.
Launcher page at http://example.com/launcher.htm
<html>
<head>
<title>postMessage launcher</title>
<script>
function openWnd() {
var w = window.open("", "theWnd", "resizeable,status,width=400,height=300"),
i = w.document.createElement("iframe");
i.src = "http://example.net/remote.htm";
w.document.body.appendChild(i);
w.addEventListener("message", function (e) {
console.log("message from " + e.origin + ": " + e.data);
// Send a message back to the source
e.source.postMessage("reply", e.origin);
});
}
</script>
</head>
<body>
<h2>postMessage launcher</h2>
<p>click me</p>
</body>
</html>
Remote page at http://example.net/remote.htm
<html>
<head>
<title>postMessage remote</title>
<script>
window.addEventListener("message", function (e) {
alert("message from " + e.origin + ": " + e.data);
});
// Send a message to the parent window every 5 seconds
setInterval(function () {
window.parent.postMessage("hello", "*");
}, 5000);
</script>
</head>
<body>
<h2>postMessage remote</h2>
</body>
</html>
I'm not sure how fragile this is, but it is working in IE 11 and Firefox 40.0.3.
Right now, (2014-09-02), Your best bet is to use a proxy frame as noted in the msdn blog post that details a workaround for this issue: https://blogs.msdn.microsoft.com/ieinternals/2009/09/15/html5-implementation-issues-in-ie8-and-later/
Here's the working example: http://www.debugtheweb.com/test/xdm/origin/
You need to set up a proxy frame on your page that has the same origin as the popup. Send information from the popup to the proxy frame using window.opener.frames[0]. Then use postMessage from the proxy frame to the main page.
This solution involves adding the site to Internet Explore's Trusted Sites and not in the Local Intranet sites. I tested this solution in Windows 10/IE 11.0.10240.16384, Windows 10/Microsoft Edge 20.10240.16384.0 and Windows 7 SP1/IE 10.0.9200.17148. The page must not be included in the Intranet Zone.
So open Internet Explorer configuration (Tools > Internet Options > Security > Trusted Sites > Sites), and add the page, here I use * to match all the subdomains. Make sure the page isn't listed in the Local intranet sites (Tools > Internet Options > Security > Local Intranet > Sites > Advanced). Restart your browser and test again.
In Windows 10/Microsoft Edge you will find this configuration in Control Panel > Internet Options.
UPDATE
If this doesn't work you could try resetting all your settings in Tools > Internet Options > Advanced Settings > Reset Internet Explorer settings and then Reset: use it with caution! Then you will need to reboot your system. After that add the sites to the Trusted sites.
See in what zone your page is in File > Properties or using right click.
UPDATE
I am in a corporate intranet and sometimes it works and sometimes it doesn't (automatic configuration? I even started to blame the corporate proxy). In the end I used this solution https://stackoverflow.com/a/36630058/2692914.
This Q is old but this is what easyXDM is for, maybe check it out as a potential fallback when you detect a browser that does not support html5 .postMessage :
https://easyxdm.net/
It uses VBObject wrapper and all types of stuff you'd never want to have to deal with to send cross domain messages between windows or frames where window.postMessage fails for various IE versions (and edge maybe, still not sure 100% on the support Edge has but it seems to also need a workaround for .postMessage)
MessageChannel doesn't work for IE 9-11 between windows/tabs since it relies on postMessage, which is still broken in this scenario. The "best" workaround is to call a function through window.opener (ie. window.opener.somefunction("somedata") ).
Workaround in more detail here

xmlhttprequest always returning status 0 even client and server on same machine

i know this questions asked several times, and i am referring all these post, even after that also not able to solve my problem. I have created a html page for client server communication. Here is the code
<!DOCTYPE html>
<html>
<head>
<title>Sandbox</title>
<script type="text/javascript">
function log (text) {
document.getElementById("contents").innerHTML = document.getElementById("contents").innerHTML + "<br />" + text;
}
function ready() {
log("Ready.");
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
log("State: " + xmlhttp.readyState + ", Status: " + xmlhttp.status
+ ", Statustext: " + xmlhttp.responseText);
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
log("CSV Content:");
log(xmlhttp.responseText);
}
};
log("Open.");
xmlhttp.open("GET", "http://10.5.13.142/iptvservice.xml", false);
log("Send.");
xmlhttp.send(null);
log("Sent.");
window.removeEventListener('DOMContentLoaded', ready, false);
}
window.addEventListener('DOMContentLoaded', ready, false);
</script>
</head>
<body>
<div id="contents">Loading.</div>
</body>
</html>
server is a Apache server.I am running this page on a same machine where server installed. On Mozilla status code is 0 and on It hanged on loading. I am not getting what is the problem. i have read that you don't need to set the permission on manifest.json if you are on the same domain. Then where i am getting wrong. Please help.
Edit: Actually my requirement is to run this code on android using phonegap. So i want to do using java script. So anybody can suggest using xmlhttprequest how to create client server connection.
sorry, but just now i got this link
XMLHttpRequest Fails On Same Domain
but in my case Apache server giving xml page. So where i should put my script.and this is just for testing purpose i am using same machine, but after that i need to run same page on different machine. Then what would be the solution. sorry i am asking very simple question, but required little help.
Edit: just for information. I did change according to the link
http://www.skill-guru.com/blog/2011/02/04/adding-access-control-allow-origin-to-server-for-cross-domain-scripting/
and then ran on google chrome, it worked, but it still not working on firefox. Anyways, atleast my code and server installation is proper.

Dojo Comet + Orbited is giving 404

I have
<script type="text/javascript">
function setupComet()
{
dojox.cometd.init("http://comet.domain.tld:8000");
dojox.cometd.subscribe("/my/calendar", cometCallback);
}
dojo.addOnLoad(setupComet);
function cometCallback (msg)
{
alert(msg.data);
}
</script>
Orbited is replying (viewed with firebug):
<html>
<head><title>404 - No Such Resource</title></head>
<body>
<h1>No Such Resource</h1>
<p>No such child resource.</p>
</body>
</html>
What I'm doing wrong?
What I'm trying to achieve:
Browser comes to page and subscribes to (read-only) channel. When browser sends POST data, PHP side will send data to database and then publish 'refresh' to that comet channel. Browser gets this and refreshes page.
/etc/orbited.cfg:
[global]
reactor=epoll
session.ping_interval = 40
session.ping_timeout = 30
user=orbited
[listen]
http://:8000
[static]
[access]
* -> localhost:8000
* -> dev.lan:80
[logging]
debug=STDERR,debug.log
info=STDERR,info.log
access=STDERR,info.log
warn=STDERR,error.log
error=STDERR,error.log
enabled.default=info,access,warn,error,debug
You are trying to use the cometd library with the Orbited server. These two things do not go together -- just use Orbited.js. It should work with all of your other dojo code just fine.