2010-04-08 149 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应该让你。