使用JavaScript进行URL检测 [英] URL detection with JavaScript

查看:97
本文介绍了使用JavaScript进行URL检测的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下脚本强制将特定页面(首次加载时)强制转换为(第三方)iFrame。

I'm using the following script to force a specific page - when loaded for the first time - into a (third-party) iFrame.

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

(澄清:此'嵌入'由第三方系统自动完成,但仅限于页面刷新一次 - 因为样式和其他一些原因我从一开始就想要它。)

(For clarification: This 'embedding' is done automatically by the third-party system but only if the page is refreshed once - for styling and some other reasons I want it there from the beginning.)

现在,我想知道这个脚本是否可以通过各种方式增强它能够检测其父文档的当前URL以触发特定操作吗?假设第三方网站的网址是 http://cgi.site.com/hp/ ...'和iFrame的网址' http://co.siteeps.com/hp / ......。是否有可能实现......与JS一样:

Right now, I'm wondering if this script could be enhanced in ways that it's able to detect the current URL of its 'parent' document to trigger a specific action? Let's say the URL of the third-party site is 'http://cgi.site.com/hp/...' and the URL of the iFrame 'http://co.siteeps.com/hp/...'. Is it possible to realize sth. like this with 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 josh

推荐答案

<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>

当然,第二个if是多余的,所以你可以这样做:

Of course, the second if is redundant so you can simply do this:

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

你在这里做的是测试 window.location 使用正则表达式查看它是否与您想要的URL匹配。

What you're doing here is testing window.location with a regular expression to see if it matches the URL you want.

如果要引用父URL,可以使用 parent.location.href

If you want to refer to the parent's URL, you can use parent.location.href.

根据您的评论,如果您想要做某事 else 你可以这样做:

Per your comment, in the event that you want to do something else you can do something like this:

<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(没有操作)所以你甚至不需要那里的其他(或其他的if),因为它将是一个空块。

If you're doing nothing in the other case, that's effectively a NOP (no operation) so you don't even need the else there (or another if) since it's going to be an empty block.

这篇关于使用JavaScript进行URL检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆