SystemicPlural
SystemicPlural

Reputation: 5789

Is it possible to send a function to another window using postMessage without having to eval it?

postMessage only accepts strings, so it has to be converted to a string (which isn't a problem). However once it is there it needs to be executed. What is the best way to do this?

Upvotes: 0

Views: 1257

Answers (1)

robertc
robertc

Reputation: 75717

Don't send a function, and certainly don't eval anything you receive in an onmessage event - it could come from anywhere.

Cross document messaging is a designed hole in the same origin security policy implemented by browsers, if you're going to purposely work around that policy its incumbent on you to understand what you're doing and handle the security yourself. By calling eval on you're basically offering to run on your page, presumably containing your user's data, any JavaScript a hacker can trick your page into accepting.

A better way to do it is to whitelist the allowed operations and then select among them based on what's passed into onmessage.

function receiveMessage(event)
{
  // Do we trust the sender of this message?
  // Test for the domain that will be sending messages
  if (event.origin !== "http://example.com:")
    return;

  if (event.data == 'command1') doCommand1(); //define these functions elsewhere
  if (event.data == 'command2') doCommand2(); //note no data is passed from the event
}

window.addEventListener("message", receiveMessage, false);

If you want to pass parameters then use JSON.stringify(). If there's a predefined set of parameters you expect then you can use the same approach as above, no need to ever pass a string from a potentially unknown source direct into your code. If you do need to deal with a variable parameter then take all the standard precautions with a string from an unknown source.

Upvotes: 1

Related Questions