Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax error for cross domain messaging

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" } ' + '}');
like image 933
user2104778 Avatar asked Sep 20 '13 20:09

user2104778


1 Answers

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?

like image 199
bfavaretto Avatar answered Nov 15 '22 10:11

bfavaretto