On Mon, Oct 22, 2012 at 2:06 PM, mrtn <
mrtn...@gmail.com> wrote:
> I get Uncaught Error: INVALID_STATE_ERR when I run the following within a
> closure:
>
> function connect() {
> var options = {protocols_whitelist: ["websocket", "xhr-streaming",
> "xhr-polling", "iframe-htmlfile", "iframe-xhr-polling",
> "iframe-eventsource"], debug: true};
> conn = new SockJS("
http://www.playmymodel.com/sockjs/wait", options);
> conn.onopen = function() { console.log("connected"); };
>
> ...
> }
>
> connect();
>
> if (conn != null) {
> var initialMsg = JSON.stringify({"subject": "hello", "content": "hello
> world"});
> conn.send(initialMsg);
> console.log("initial msg sent");
> }
>
> I suspect that the problem is that I send the msg too soon before the
> connection is fully established.
Correct. You can't call 'send' before onopen event is fired or after
'onclose' event.
> So how can I programmatically make sure
> that I send the first msg only after the connection is fully established
> (i.e. after 'onopen' callback is executed)?
Option #1: install onopen handler and do 'send' in it
Option #2: verify if 'conn.readyState' == SockJS.OPEN
> P.S. I want the 'initialMsg' to be sent automatically after the page is
> loaded in the browser, so a solution involving manual control of sending the
> msg is not suitable for this case.
Beware - establishing sockjs connection may take longer than loading
your page.
Marek