通过消息将数据传递给iframe时不更改原点

时间:2017-04-13 12:55:26

标签: javascript jquery iframe greasemonkey tampermonkey

假设我有2页: foo.com和bar.com 我使用Tapermonkey在每个脚本上运行脚本。我想在foo.com上编写脚本,将数据传递给bar.com上的脚本。 因为foo和bar在不同的域上,所以我无法直接传递数据(GM_setValue,localStorage,webSQL)。

但我找到了这个教程: https://jcubic.wordpress.com/2014/06/20/cross-domain-localstorage/

诀窍是将iframe与bar.com连接到foo.com,通过postMessage发送数据,iframe接收数据并将其保存到localstorage。然后foo.com上的第二个脚本将能够从localstorage中读取数据。

这是第一个脚本:

var name = "John";
var div = document.createElement('div');
div.id = "result";
document.body.appendChild(div);   
var barPage = 'http://bar.com/';
document.getElementById("result").innerHTML = "<iframe src='"+ barPage +"' width='100%' height='100px' id='bariframe' />";

$(document).ready(function() {
    var win = div.children[0].contentWindow;

    var script = "window.addEventListener('message',function(e){if(e.origin!=='http://bar.com/'){console.log('wrong origin: '+e.origin);return}alert(e.data);var payload=JSON.parse(e.data);localStorage.setItem(payload.key,JSON.stringify(payload.data))});";

    var scriptObj = win.document.createElement("script");
    scriptObj.type = "text/javascript";
    scriptObj.id = "barscript";
    scriptObj.innerHTML = script;
    win.document.body.appendChild(scriptObj);        

    var obj = {
        "name": name
    };
    var json = JSON.stringify({key: 'storage', data: obj});
    win.postMessage(json, "*");
    console.log("Sent: " + json);
});

什么脚本可以:

1)创建空div并将其添加到foo.com底部

2)文档加载后我将javascript注入iframe并通过postMessage发送数据

3)注入的脚本应该接收数据并将其保存到localStorage。

但问题是我仍然在该剧本中获得foo.com。它应该是bar.com,不应该吗?

因为当我真的打开foo.com脚本时,这里不会有这些数据。

为什么不起作用?

1 个答案:

答案 0 :(得分:0)

由于“相同的来源政策”,您无法在正在创建的跨国家iframe内进行访问,以便通过这种方式向其添加任何内容。

您需要一个bar.com的html页面,其中包含postMessage侦听器,以使您的方法正常工作