我有一个文件index.html
,其中一个iframe设置,iframe源指向另一个域。我在index.html
设置了localstorage并尝试获取iframe源中的值。(sample.html
)
File 1
index.html
<html>
<head>
//js file
</head>
<body>
setting localstorage
Iframe src="55.10.45.045/sample.html"
</body>
</html>
file 2
sample.html
<html>
<head>
//js file
</head>
<body>
getting localstorage Item //Returns null
</body>
</html
答案 0 :(得分:1)
你想要使用这样的东西。
发送信息:
window.onload = function() {
var win = document.getElementById('iFrameId').contentWindow;
win.postMessage(JSON.stringify({
key: 'dataKey',
data: dataPassing
}), "*");
};
收到信息:
window.onmessage = function(e) {
var payload = JSON.parse(e.data);
localStorage.setItem(payload.key, payload.data);
};
这会将JSON对象传递给iFrame,然后框架中的脚本将把它带到本地存储中。
答案 1 :(得分:0)
像这样使用......
的index.html
<!DOCTYPE html>
<html>
<body>
<div id="result"></div>
<a href="sample.html">click</a>
<script>
// Check browser support
if (typeof(Storage) !== "undefined") {
// Store
localStorage.setItem("link", "http://www.w3schools.com/");
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("link");
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
}
</script>
</body>
</html>
sample.html
<!DOCTYPE html>
<html>
<body>
<div id="result"></div>
<script>
// Check browser support
if (typeof(Storage) !== "undefined") {
document.getElementById("result").innerHTML = "<iframe src='"+localStorage.getItem("link")+"' width='100%' height='350px' />";
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
}
</script>
</body>
</html>