7

below is my code. I am trying to receive data from a website using cross-domain messaging. When I click the runit button, I keep getting the following error: "Uncaught SyntaxError: An invalid or illegal string was specified." Please help me identify the problem, I am at a loss.

html code:

<html>
<script language="JavaScript">

function runit() {
    alert("here");
    // Get the iframe window object
    var client = document.getElementById('client');
    // Create the data string to be passed to the OPS JavaScript
    var data = "{'url' : 'http://ops.epo.org/3.0/rest-services/published-data/publication/epodoc/EP1000000/biblio', " + "'method' : 'GET', " + "'requestHeaders' : {'Origin': 'ops.epo.org', 'Accept': 'application/json' } " + "}";
    alert(data);
    // Use the postMessage() method in order to send the data to the
    // iframe object
    client.contentWindow.postMessage(data, 'ops.epo.org');
}
// Add event listener for your window
window.addEventListener("message", receiveMessage, false);
// Method handling window events
function receiveMessage(event) {
    alert("here");
    // Check origin of the event!
    if (event.origin == "http://ops.epo.org") {
        var dataJSON = eval('(' + event.data + ')');
        // work with data / display data
        alert(dataJSON);
    } 
    else {
        alert("Got message from unknown source.");
    }
}    

</script>
<body>
    <input type="button" onclick="runit()" value="runit"></input>
    <iframe width=100 height=100 id="client" src="http://ops.epo.org/3.0/xss/crosssitescript.html" />
</body>
</html>

EDIT: I tried double quotes for the data string, and JSON.stringify, and it didn't work:

    var data = JSON.stringify('{"url" : "http://ops.epo.org/3.0/rest-services/published-data/publication/epodoc/EP1000000/biblio", ' + '"method" : "GET", ' + '"requestHeaders" : {"Origin": "ops.epo.org", "Accept": "application/json" } ' + '}');
user2104778
  • 992
  • 1
  • 14
  • 38

1 Answers1

8

You have to pass the protocol of the targetOrigin when you call postMessage:

client.contentWindow.postMessage(data, 'http://ops.epo.org');

This also works, but may have security implications:

client.contentWindow.postMessage(data, '*');

I peeked at the documentation for what you're trying to do, and there's also the option to use JSONP. Why not just use that, since it's simpler and probably better supported?

bfavaretto
  • 71,580
  • 16
  • 111
  • 150
  • bfavaretto - points well earned. See [here](http://jsfiddle.net/6zCgA/1/). Also, JSONP cannot be used for all the functionality of this website. – user2104778 Sep 20 '13 at 21:19
  • 1
    It's really weird that the error produced by putting in the wrong origin is specifically a syntax error. And it's only a syntax error in some browser and not others. – Kevin Beal Aug 03 '15 at 20:37