开发者

passing in javascript values into iframe tag

开发者 https://www.devze.com 2022-12-26 19:40 出处:网络
What\'s the best way to pass in the value held in a javascript variable into an iframe call on the same html page? I\'m trying to improve my site\'s page response times by moving ad serving javascript

What's the best way to pass in the value held in a javascript variable into an iframe call on the same html page? I'm trying to improve my site's page response times by moving ad serving javascript code (the typical document.write('<script type="text/javascript" src="..") into a separate iframe. (Based on this posting)

The request to the ad server typically require a seed variable declared once per site and incremented each time page is loaded by the client. What I want to do is pass in the seed variable into the document invoked by my iframe section.

The seed variable is initialized in the 'head' tag of my main html docume开发者_运维百科nt:

<head>
    <script type="text/javascript">
    <!--
    custom_seed=1;  
    //-->
    </script>
</head>

Later in the html document, I make the request through an iframe which returns the html necessary to invoke the ad server.

<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>

The html returned in the 'somepage.html' has a script used to call the ad server and needs to use the earlier declared seed variable as a parameter:

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

What's a good way to achieve this?


The only way you can pass values directly to an iframe of a page with a different domain is through the url, as querystring values, anchors, or perhaps some form of rewriting. Even if it's on the same domain, that's probably the easiest and safest way to pass it.

Main document:

document.getElementById('IframeID').src = "somepage.html?seed=" + custom_seed;

Inner document:

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


Here's a neat workaround with no ugly url variables. While you can't send variables into an iframe, you can call a function to run.

Begin by programming a function in the destination page to receive and set the variable:

<script type="application/javascript">
    function variable(value) {
        var seed = value;
</script>

Then all you need to do is call the function from the origin page:

<script type="application/javascript">
    document.getElementById("IframeID").contentWindow.variable("value");
</script>


A simple away to get the value in iframe file :

  document.getElementById("youfiled").value="";

And use the echo php $_GET['seed'];

inside of the coma element;

0

精彩评论

暂无评论...
验证码 换一张
取 消