【问题标题】:Prevent iframe from being redirected to identical adress防止 iframe 被重定向到相同的地址
【发布时间】:2014-09-25 23:51:49
【问题描述】:

我想防止 iframe 被重定向到当前加载在其中的同一地址。我想这样做的原因是,当您被重定向到完全相同的页面时,我想防止不必要的白色闪烁。

这是一个 jsfiddle http://jsfiddle.net/8zs8mh5d/

<a href="http://www.randomwebsite.com/" target="tc">dont redirect if not from link 3</a><br>

<a href="http://www.randomwebsite.com/" target="tc">dont redirect if not from link 3</a><br>

<a href="http://day.smakkie.com/" target="tc">dont redirect if not from link 1 or 2</a><br>

<iframe id="truecontent" name="tc" src="http://www.randomwebsite.com/"></iframe>



#truecontent
{
    height:200px;
    width:400px;
}

【问题讨论】:

    标签: javascript html redirect if-statement iframe


    【解决方案1】:

    你可以像这样使用 JavaScript:

     function confirmTarget(target) {
      current = document.getElementById('truecontent').getAttribute('src');
      if(current != target)
       document.getElementById('truecontent').src = target;
     }
    

    并修改您的链接,例如:

    <a href="#" onclick="confirmTarget('http://www.randomwebsite.com/')">dont redirect if not from link 3</a><br />
    <a href="#" onclick="confirmTarget('http://www.randomwebsite.com/')">dont redirect if not from link 3</a><br />
    <a href="#" onclick="confirmTarget('http://day.smakkie.com/')">dont redirect if not from link 1 or 2</a><br />
    

    这是一个 JSFiddle:http://jsfiddle.net/5xs3tnze/2/

    【讨论】:

      【解决方案2】:

      您可能需要一点 JavaScript 帮助。像这样定义你的链接:

      <a href="#" onclick="redirectIframe('http://www.randomwebsite.com/', 'tc')">dont redirect if not from link 3</a><br>
      
      <a href="#" onclick="redirectIframe('http://www.randomwebsite.com/', 'tc')">dont redirect if not from link 3</a><br>
      
      <a href="#" onclick="redirectIframe('http://day.smakkie.com/', 'tc')">dont redirect if not from link 3</a><br>
      
      <br>
      
      <iframe id="truecontent" name="tc" src="http://www.randomwebsite.com/"></iframe>
      

      然后添加重定向功能

      function redirectIframe(url,name) {
          var iFrame = document.getElementsByName(name)[0];
      
          if (iFrame.src != url) iFrame.src = url;
      }
      

      函数将检查您重定向到的 URL 是否与当前 IFRAME 源相同,如果是这种情况,则返回而不重定向。

      演示:http://jsfiddle.net/8zs8mh5d/1/

      【讨论】:

        猜你喜欢
        • 2013-03-12
        • 2020-04-28
        • 2021-01-10
        • 2014-03-10
        • 2020-04-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多