在我的HTML页面中,我使用了iframe。在这个 iframe 中,我展示了一个条形图。我想将数据从我的HTML页面传输到iframe,而无需GET或POST数据。如何在 iframe 链接中使用数据?是否可以在 iframe 链接中使用此变量,该变量在其他页面中可见或看不到?
如果是,这是可能的,那么我们如何实现它 如果没有,那么我们遵循什么方式来实现这一点。
页 1.html
<iframe id="iframe1" data-value="yourdata" src="page2.html"></iframe>
页2.html
<script type="text/javascript">
alert(parent.document.getElementById("iframe1").getAttribute("data-value"));
</script>
希望这有帮助。
1(解决方案:location.hash
索引.html
<iframe src="iframe.html#extraHashDataNotSendToServer"></iframe>
iframe.html
<script type="text/javascript">
console.log(location.hash); // "#extraHashDataNotSendToServer"
</script>
2(解决方案:窗口发布消息(...(
索引.html
<iframe src="iframe.html" name="target">
<script>
var win = window.frames.target;
// Send message to iframe.html
win.postMessage('Message to iframe', '*');
// Get message from iframe.html
window.addEventListener('message', e => {
console.log(e.data); // "Mess from iframe"
})
</script>
iframe.html
<script>
// Send message to index.html
window.parent.postMessage('Mess from iframe', '*');
// Get message form index.html
window.addEventListener('message', e => {
console.log(e.data); // "Message to iframe"
})
</script>
GitHub 页面上的演示和 GitHub 上的代码
这是第一个.html
window.onload = function() {
var varObject = {label:["January", "February", "March", "April", "May", "June", "July"], data:[65, 59, 20, 81, 56, 55, 40]};
var child = document.getElementById("child");
var childWindow = child.contentWindow;
childWindow.postMessage(JSON.stringify(varObject),'*');
console.log(childWindow.postMessage);
}
这是塞昆德.html
if(window.addEventListener){
window.addEventListener("message", getData, false);
} else {
window.attachEvent("onmessage", getData);
}
function getData(e){
let data = JSON.parse(e.data);
alert('test');
console.log(data);
}
谢谢大家,您的建议使我的答案创建非常感谢。 你节省了我的时间