开发者

How to stop iFrame from reloading

开发者 https://www.devze.com 2023-03-20 03:40 出处:网络
I am trying to pass a parameter to an iFrame by adding a param in the onload event as below: <iframe name=\"myframe\" src=\"http://test.com/hello\" onload=\" frames[\'myframe\'].location.href=\'ht

I am trying to pass a parameter to an iFrame by adding a param in the onload event as below:

<iframe name="myframe" src="http://test.com/hello" onload=" frames['myframe'].location.href='http://test.com/hello?uname='+getUserName();">

</iframe>

(getUserName is my custom function)

But the iFram开发者_如何学编程e keeps loading over and over again. How do I stop this using just javascript (and not any js framework)?

Note:For certain reasons, I can write only inline javascript scripts.


You can set a global flag (choose an appropriate name that does not collide with any other name):

if (window.frames['myframe'] && !window.userSet){
    window.userSet = true;
    frames['myframe'].location.href='http://test.com/hello?uname='+getUserName();
}

Alternatively you can set a custom attribute to the element:

var userSet = this.getAttribute('data-userset');
if (window.frames['myframe'] && !userSet){
    this.setAttribute('data-userset', 'true');
    frames['myframe'].location.href='http://test.com/hello?uname='+getUserName();
}

Or if you don't have to invoke the event handler later on again, you can remove it:

if (window.frames['myframe']){
    this.onload = null;
    this.setAttribute('onload', '');
    frames['myframe'].location.href='http://test.com/hello?uname='+getUserName();
}

Btw. what do you have the if statement for? I think it will always be true anyway.


because the HREF is changing on the onload and Change of HREF will reload the iFrame.

So you have to remove the onload to some other event.


Use a counter so that only the first time it redirects.

Initially it is 0 and redirects, the second time it is 1, etc and hence does not redirect.

<script>var counter = 0</script>

<iframe name="myframe" src="http://test.com/hello"
 onload="if (window.frames['myframe'] && counter++ === 0){ frames['myframe'].location.href='http://test.com/hello?uname='+getUserName();}">
</iframe>
0

精彩评论

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