我创建了一个JS文件,我放在除了我的一些网页之外.所以我的是domain-1.com,我把它放到domain-2.com和domain-3.com
这个JS包含jsonp,我将其页面中的一些数据成功保存到我的数据库中.此外,我创建了一些cookie,并将值保存到localstorage.问题是,当访问者访问domain-2.com并明天访问www.domain-2.com时,他们将拥有不同的价值,因为它是www.
我希望这个值在整个www中都是一样的.或不,也许在同一时间,我不知道一个适用的想法.我最好同时为www传递值.没有www.
这该怎么做?我只为他们提供了一个JS外部链接.没关系,如果我也放置iframe.
最好的解决方案是设置重定向到任一域,这样您就可以完全避免这个问题.
以下代码显示了将值发送到非www域以进行存储的概念.如果您还需要从www域中读取这些值,或者希望库为您执行所有操作,则应使用最后列出的库之一.这些库使用相同的概念,但会为您处理大多数事情.
您可以仅将值存储在一个域中,如果您在www域上,则使用跨源通信发送值.创建一个iframe加载非www域的脚本.在此脚本中,您将值保存在该域的本地存储中.
以下是iframe的内容,其中包含一些最小的html5标记,在此示例中保存为storage.html和提供example.com.
<!DOCTYPE html>
<html><head><meta charset="utf-8"><title> </title>
<script>
window.addEventListener("message", storeItem, false);
function storeItem(event) {
if (!(event.origin == "http://example.com" || event.origin == "http://www.example.com")) {
return;
}
localStorage.setItem(event.data.key, event.data.value);
}
</script>
</head></html>
Run Code Online (Sandbox Code Playgroud)
当您想要存储数据用于postMessage与iframe通信时.需要先加载iframe才能发送消息.
<iframe id="storageScriptFrame"></iframe>
<script>
var target = "http://example.com";
var storageScriptFrame = document.getElementById("storageScriptFrame");
var storageScriptWindow = storageScriptFrame.contentWindow;
function storeItem(key, value) {
var message = {key: key, value: value};
storageScriptWindow.postMessage(message, target);
}
// you can store values after the iframe has loaded
storageScriptFrame.onload = function() {
storeItem("foo", "bar");
};
// replace this with actual page
storageScriptFrame.src = 'http://example.com/storage.html';
</script>
Run Code Online (Sandbox Code Playgroud)
确保将example.com域替换为实际域.检查原始域很重要,因此其他站点无法向您发送消息.
在某些时候,您还需要读取这些存储的值.根据您对存储值的处理方式,您有两种选择.
postMessage再次使用以返回值.第二个选项可能会变得复杂,因为它postMessage是异步的,只能以一种方式工作.我建议使用现有的库来执行此操作(您不需要上面的代码).
例如,如果你跨域本地存储你只需要按照安装说明,并在initCallback功能,你可以打电话xdLocalStorage.getItem和xdLocalStorage.setItem获得和的localStorage的设置项目example.com.
| 归档时间: |
|
| 查看次数: |
1501 次 |
| 最近记录: |