2010-04-08 153 views
5

我正在使用以下腳本將第一次加載時的特定頁面強制爲(第三方)iFrame。使用JavaScript進行URL檢測

<script type="text/javascript"> 
    if(window.top==window) { 
     location.reload() 
    } else { 
    } 
</script> 

(爲了澄清:此「嵌入」自動由第三方系統只有在頁面被刷新一次完成,但 - 對於造型和其他一些原因,我想它從一開始就。)

現在,我想知道是否可以通過能夠檢測其「父」文檔的當前URL來觸發特定操作的方式來增強此腳本?假設第三方網站的網址爲'http://cgi.site.com/hp/ ...',iFrame的網址爲'http://co.siteeps.com/hp/ ...'。有可能實現某事嗎?像這樣用JS:

<script type="text/javascript"> 
    if(URL is 'http://cgi.site.com/hp/...') { 
     location.reload() 
    } 
    if(URL is 'http://co.siteeps.com/hp/...') { 
     location.do-not.reload() resp. location.do-nothing() 
    } 
</script> 

TIA喬希

回答

7
<script type="text/javascript"> 
    if(/^http:\/\/cgi.site.com\/hp\//.test(window.location)) { 
     location.reload() 
    } 
    if(/^http:\/\/co.siteeps.com\/hp\//.test(window.location)) { 
     location.do-not.reload() resp. location.do-nothing() 
    } 
</script> 

當然,如果是多餘的,所以你可以簡單地這樣做第二:

<script type="text/javascript"> 
    if(/^http:\/\/cgi.site.com\/hp\//.test(window.location)) { 
     location.reload() 
    } 
</script> 

你在做什麼在這裏用正則表達式測試window.location,看看它是否與你想要的URL匹配。

如果你想引用父母的URL,你可以使用parent.location.href

根據您的評論,在你想要做的事其他事件你可以做這樣的事情:

<script type="text/javascript"> 
    if(/^http:\/\/cgi.site.com\/hp\//.test(window.location)) { 
     location.reload() 
    } 
    else if(/^http:\/\/co.siteeps.com\/hp\//.test(window.location)) { 
     //do something else 
    } 
</script> 

如果你在其他情況下,這樣做什麼,這實際上是NOP(無操作),所以你甚至不需要在那裏(或另一個),因爲它將是一個空的塊。

+0

嗨! thx爲您的即時回覆!我應該定義什麼,而不是'location.do-not.reload()resp。 location.do全無()「? – josh 2010-04-08 00:20:29

+0

是如果...如果...可能與js?或者我需要一個'其他'? – josh 2010-04-08 00:21:22

+0

假設我理解你的邏輯流程正確,你只*想要執行重載,如果URL匹配'http:// cgi.site.com/hp'。如果是這樣的話,你不需要別的東西,因爲你真的沒有做任何事情。當然,如果你想做其他的事情,那麼你可以使用'else if(...){...}' – 2010-04-08 00:23:47

2

您可以使用window.location.href來獲取URL以進行字符串比較。如果你在一個iframe,並需要知道父母的URL parent.location.href應該讓你。