简体   繁体   English

如何使用 javascript 从 iframe 访问父级的 JSON object

[英]How to access parent's JSON object from iframe using javascript

I have a html code like below.我有一个 html 代码,如下所示。

index.html索引.html

<html>
<head>
 <script>
  user_data = {
  name: 'xyz',
  age: 123
 }
</script>
</head>
<body>
.... some code ---
<iframe src="test.html"></iframe>
</body>
</html>

test.html测试.html

<html>
<head>
 <script>
 $(document).ready(function(){
var userName = user_data.name;
});
</head>
<body>
<!--- some other code -->
</body>
</html>

Basically, I am trying to access user_data object which is in index.html from test.html (iframe file).基本上,我正在尝试从 test.html(iframe 文件)访问 index.html 中的 user_data object。

Can somebody help me to get the value in iframe.有人可以帮我获得 iframe 的价值吗?

First move your script from head to body.首先将脚本从头部移动到身体。

 <html> <head> <title>Parcel Sandbox</title> <meta charset="UTF-8" /> </head> <body> <h1>Parent</h1> <iframe src="./test.html"></iframe> <script> user_data = { name: "xyz", age: 123 }; </script> </body> </html>

Then access parent data with window.parent然后使用window.parent访问父数据

<body>
    <h1>Test Html</h1>
    <div id="app"></div>
    <script>
        const { parent = {} } = window;
        const { user_data = {} } = parent;
        const { name, age} = user_data;
        const $app = document.getElementById('app')
        $app.innerText = `name: ${name}, age: ${age}`
    </script>
</body>

Here is a code sample这是一个代码示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM