2014-09-24 93 views
2

我想打開一個IFrame內的新選項卡。我試圖讓觸發點擊事件看起來好像它是從IFrame外部啓動的。模擬IFrame中的點擊,打開新選項卡。

page.html中

<div> 

<iframe src="page1.html"> 

</iframe> 

page1.html

<a href="path_to_other_page" id="link_to_other_page" target="_blank">link</a> 

如果用戶點擊,但我需要的標籤自動打開上面會打開一個新標籤。

<script> 
    parent.window.open('/path_to_other_page', '_blank'); //will open a new window rather than tab but could be blocked 

    $(function() 
    { 
     $("#link_to_other_page")[0].click(); //opens in new window How do make the 
     //click appear to be initiated from outside the iframe so a new tab opens? 
    }); 
</script> 

問題: 如何模擬點擊鏈接,以便點擊似乎是從外面IFRAME啓動?

############ 
+2

'target =「_ blank」'? – Alex 2014-09-24 11:13:21

+0

@Alex在iframe中不起作用。 – 2014-09-24 22:48:39

+3

@NickMaroulis - 這根本不可能。如果您對彈出窗口(寬度,高度,隱藏地址欄等)施加限制,瀏覽器將決定如何處理鏈接。因此,用戶將瀏覽器配置爲在新選項卡中打開新窗口將會是一個問題。現在還沒有辦法強制一個標籤放在窗戶上。至於使iframe鏈接寄存器在幀外發生,您可以創建一個僞幀來模擬iframe的功能,同時保持標準頁面功能。 – 2014-09-26 12:35:31

回答

1

給ID的iFrame和嘗試下面的代碼: -

<script type="text/javascript"> 
    $(document).ready(function() { 
     $("#iframeID").load(function() { 
      var ifr = document.getElementById("iframeID") 
      var anchors = iframeID.contentDocument.getElementsByTagName("a"); 
      for (var i in anchors) { 
       anchors[i].setAttribute("target", "_blank"); 
      } 
     }); 
    }); 
</script> 

希望它有助於

+0

這可能會打開一個新窗口而不是新標籤頁。提問者要求打開新標籤。我在回答中注意到了這一點。你不必爲此而投票。 – vrijdenker 2014-09-24 11:26:37

2
<a href="path_to_other_page" id="link_to_other_page" target="_blank">link</a> 

你並不需要的JavaScript。

請注意,無論瀏覽器是打開新窗口還是新選項卡,都無法強制執行。這是在瀏覽器(和用戶通過瀏覽器設置)來決定的。

+0

+1,指出這是一個瀏覽器問題。已經花了太長時間找出如何強制瀏覽器打開新標籤,直到我發現你不能。 – 2014-10-01 12:31:56

2

首先,主頁面和iframed頁面應該存在於同一個域中。

然後,假設裏面你的鏈接的iFrame頁面已具有target="_blank"屬性,它的需要(因爲它已經在以前的答案指出),如:

<a href="path_to_other_page" id="link_to_other_page" target="_blank">link</a> 

...你可以添加這個腳本的主網頁:

jQuery(document).ready(function ($) { 
    $("#myIframe").load(function() { 
     var link = document.getElementById("myIframe").contentDocument.getElementById("link_to_other_page"); 
     $(link)[0].click(); 
    }); 
}); // ready 

...或者,如果你喜歡的jQuery的方式

jQuery(document).ready(function ($) { 
    $("#myIframe").load(function() { 
     var link = $("#myIframe").contents().find("#link_to_other_page"); 
     $(link)[0].click(); 
    }); 
}); // ready 

考慮

  • 您可能需要設置一個ID您標籤(#myIframe),這樣你可以操縱它。
  • 您使用​​方法確保在iframe完全加載之前,您不會嘗試觸發click
  • 您不需要在iframed頁面內設置任何javascript。

DEMO

注意:在我的演示中,我使用setTimeout()觸發click 5秒後,因此會更明顯。

重要:因爲前面提到的,它是由瀏覽器如何打開頁面。 Chrome會以彈出式方式打開(如果您使用的是window.open()),則任何以編程方式設置click事件的鏈接(即使手動點擊也會在新標籤中打開該頁面),而Firefox會在新標籤中打開該鏈接。

1

你可以在一個鏈接中虛擬,並在父窗口中「點擊」它。它應該更「本土化」。

<script> 
    $(function() { 
     var link_html = $("#link_to_other_page").html(); 
     parent.window.$(link_html)[0].click(); 
    }); 
</script> 

見​​爲完整的例子。

+0

值得注意的是,這個例子假定jQuery在父窗口中也是可用的。如果不是,那麼提供一個香草JS例子也是微不足道的。 – 2014-10-02 19:56:23

相關問題