javascript - 如何阻止 iFrame 重新加载

标签 javascript iframe

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

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

</iframe>

(getUserName 是我的自定义函数)

但是 iFrame 不断加载。如何仅使用 javascript(而不是任何 js 框架)来阻止它?

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

最佳答案

您可以设置一个全局标志(选择一个不与任何其他名称冲突的适当名称):

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

或者,您可以为元素设置自定义属性:

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();
}

或者如果您以后不必再次调用事件处理程序,则可以将其删除:

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

顺便说一句。您有什么 if 语句?我认为无论如何它总是 true

关于javascript - 如何阻止 iFrame 重新加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6676358/

相关文章:

c# - .NET Membership.GetUser() 在 ie9 和 safari 中嵌入到 iframe 时为 null

javascript - Css 动画不适用于 JSON 列表

javascript - 如何根据JS输出显示iframe

javascript - Youtube 是否对自己域中的视频使用 &lt;iframe&gt; 或 <video> ?

JavaScript .map 未在 React 中渲染 chrome.topSites

javascript - jQuery - iframe 内的 iframe - 就绪与加载

javascript - 嵌套的 iframe jquery 问题

javascript - 这些编写函数原型(prototype)的方法是否等效?

javascript - CSHTML 页面上的 Javascript 元素中的 C#

javascript - 动态页面中的路径替换内容