跨域消息传递的语法错误

时间:2013-09-20 20:34:41

标签: javascript cross-domain messaging

下面是我的代码。我正在尝试使用跨域消息传递从网站接收数据。当我单击runit按钮时,我不断收到以下错误:“Uncaught SyntaxError:指定了无效或非法的字符串。”请帮我确定问题,我不知所措。

html代码:

<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>

编辑: 我为数据字符串和JSON.stringify尝试了双引号,但它不起作用:

    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" } ' + '}');

1 个答案:

答案 0 :(得分:5)

当您致电targetOrigin时,您必须通过postMessage的协议:

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

这也有效,但可能会产生安全隐患:

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

我偷看了documentation你正在尝试做什么,并且还有使用JSONP的选项。为什么不使用它,因为它更简单,可能更好地支持?