Codemwnci
Codemwnci

Reputation: 54884

Fire javascript retrieved from a websocket

I am playing around with WebSockets at the moment, and I would like to have the following design pattern.

Connect to my websocket on a server, the server sends JavaScript to the browser to inform it how to interact with the user. I found the JQuery method getScript, which loads a script in the background, and executes it on load. I want to do a similar thing, but on the message received from the Websocket.

So, basically, what I want to do is...

// Create a socket
var socket = new WebSocket('myURL')

// Message received on the socket
socket.onmessage = function(event) {
    executeJS(event.data);
} 

What code would I need to replace executeJS to get this javascript to fire? Is it possible?

I suppose this question is not directly related to javascript, but how do I take a piece of text and execute it as Javascript.

Upvotes: 2

Views: 837

Answers (4)

otakustay
otakustay

Reputation: 12395

eval function evaluates code in local scope, for those code which should be evaluated in global scope, use indirect eval, a best way to call indirect eval is:

(1, eval)(yourCode);

There is also some other choice to execute code dynamically:

Also it is a good choice to use dynamic script element:

var script = document.createElement('script');

// detect browser or feature first, only one of these should be used
// for IE
script.text = yourCode;
// for other browser
script.appendChild(document.createTextNode(yourCode));

var head = document.head || document.getElementsByTagName('head')[0];
head.insertBefore(head, head.lastChild);

Upvotes: 2

Rory McCrossan
Rory McCrossan

Reputation: 337580

While it's use is generally frowned upon, the eval() function would suit your needs here, depending on the complexity of the returned code.

Upvotes: 0

ThiefMaster
ThiefMaster

Reputation: 318518

The function you are looking for is eval().

Please don't forget that it sounds like evil for a reason ;)

Upvotes: 2

T.J. Crowder
T.J. Crowder

Reputation: 1074475

Since you're using jQuery, you can use jQuery.globalEval. Alternately you could use eval, but globalEval has some advantages in terms of the context in which it runs.

Upvotes: 3

Related Questions