首页 > 解决方案 > 在 iframe 中传递 javascript 变量

问题描述

我正在尝试在 iframe 中传递 javascript 变量

这是第一个域中的 index.html

 <script>var details ='test999'</script>;
 <iframe src="http://somedomain.com/99.html" frameborder="0" width="100%" ;scrolling="yes""></iframe>

在其他域中,我正在使用以下代码上传 99.html

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>

<script>
  $(document).ready(function() {
    $("#prithere").html('' + details + '');
  });
</script>

<div id="prithere"></div>

我没有收到跨源问题我收到了这个未定义的错误。Uncaught ReferenceError: details is not defined 这是因为代码是在加载 iframe 之前执行的吗?如果是这样,有什么解决办法吗?我不能使用 onclick

标签: javascript

解决方案


如果可以的话,它parent.details只是将它传递给页面:

<script>
var details ='test999'; 
document.write('<iframe src="http://somedomain.com/99.html#details='+details+'"....</iframe>');
</script>

然后

$(document).ready(function() {
  $("#prithere").html(location.hash.split("details=")[1]);
});

推荐阅读