将javascript值传递到iframe标记

Ced*_*sen 7 html javascript ads

将javascript变量中保存的值传递到同一个html页面上的iframe调用的最佳方法是什么?我正在尝试通过将广告投放javascript代码(典型document.write('<script type="text/javascript" src="..")移动到单独的iframe 来改善网站的网页响应时间.(根据这篇文章)

对广告服务器的请求通常需要每个站点声明一次的种子变量,并在每次客户端加载页面时递增.我想要做的是将种子变量传递到我的iframe部分调用的文档中.

种子变量在我的主html文档的'head'标签中初始化:

<head>
    <script type="text/javascript">
    <!--
    custom_seed=1;  
    //-->
    </script>
</head>
Run Code Online (Sandbox Code Playgroud)

稍后在html文档中,我通过iframe发出请求,iframe返回调用广告服务器所需的html.

<body>
<!-- a bunch of html to display the page -->
<iframe src="somepage.html" width="100%" height="100%">
<p>No support for iframe</p>
</iframe>
</body>
Run Code Online (Sandbox Code Playgroud)

'somepage.html'中返回的html有一个用于调用广告服务器的脚本,需要使用先前声明的种子变量作为参数:

<script type="text/javascript">
    document.write('<script type="text/javascript" src="http://ad.server.net/...seed='+ custom_seed  +'?"></script>');
    custom_seed++;
    </script>
Run Code Online (Sandbox Code Playgroud)

有什么好办法实现这个目标?

tlo*_*lin 12

您可以将值直接传递给具有不同域的页面的iframe 的唯一方法是通过url,作为查询字符串值,锚点,或者可能是某种形式的重写.即使它在同一个域上,这可能是最简单,最安全的传递方式.

主要文件:

document.getElementById('IframeID').src = "somepage.html?seed=" + custom_seed;
Run Code Online (Sandbox Code Playgroud)

内部文件:

var seed = window.location.search.substring(window.location.search.indexOf('seed=') + 5);
if (seed.indexOf('&') >= 0) {
    seed = seed.substring(0, seed.indexOf('&'));
}
Run Code Online (Sandbox Code Playgroud)

  • 您声称无法直接将邮件发送到IFrame。那是不对的。您可以通过window.postMessage传递信息。参见https://developer.mozilla.org/en-US/docs/DOM/window.postMessage (2认同)