问题
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.)
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
回答1:
<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>
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>
What you're doing here is testing window.location
with a regular expression to see if it matches the URL you want.
If you want to refer to the parent's URL, you can use parent.location.href
.
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>
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.
回答2:
You could use window.location.href
to get the URL to do the string comparison. If you are in an iframe and need to know the parents URL parent.location.href
should get you that.
来源:https://stackoverflow.com/questions/2596749/url-detection-with-javascript