javascript 如何阻止 iFrame 重新加载

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6676358/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 21:29:14  来源:igfitidea点击:

How to stop iFrame from reloading

javascriptiframe

提问by heylo

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

我试图通过在 onload 事件中添加一个参数来将参数传递给 iFrame,如下所示:

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

(getUserName 是我的自定义函数)

But the iFrame keeps loading over and over again. How do I stop this using just javascript (and not any js framework)?

但是 iFrame 会一遍又一遍地加载。我如何仅使用 javascript(而不是任何 js 框架)来阻止它?

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

注意:由于某些原因,我只能编写内联 javascript 脚本。

回答by Felix Kling

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 ifstatement for? I think it will always be trueanyway.

顺便提一句。你有什么if声明?我想true无论如何都会是这样。

回答by Talha Ahmed Khan

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

因为 HREF 正在更改onload并且 HREF 的更改将重新加载 iFrame。

So you have to remove the onloadto some other event.

所以你必须删除onload其他一些事件。

回答by pimvdb

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

使用计数器,以便仅在第一次重定向时使用。

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

最初它是0并且重定向,第二次它是1,等等,因此不会重定向。

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