2009-06-22 59 views
47

可能重复:
Get current URL with JavaScript?请求地址

你如何获得你是在JavaScript页面的地址?

例如,如果我在somesite.com/javascript/home.html有一个脚本,并且我想查找请求地址(somesite.com/javascript/home.html),那么我如何在JavaScript中获取此信息?

+14

这怎么一个标记为欺骗,如果有人先问? – Mkalafut 2014-04-29 16:07:36

+2

生活就是不公平 - 这个复制品把这个原始的东西骗到了一个孤独的角落,偷走了所有的声望,然后说这个是重复的。 – icc97 2014-11-13 10:09:14

回答

34

您需要使用: document.locationwindow.location

你可以阅读更多here。或者对there有更多的解释。

为了澄清此事:

原帖由Mozilla开发者中心

document.location原本是 只读属性,虽然壁虎 浏览器允许您分配给它的 好。为了实现跨浏览器安全性,请改为使用 window.location。

+1

我只是使用位置! – 2009-06-23 02:48:57

12
window.location.href; 

location.href; 

window是全局对象,所以location.href将是相同的window.location.href和NOT document.location.href(只要没有封闭函数或with声明,阴影属性)

2

document.URL

8

你在找什么是window.location.href

4

我相信无论是window.location.href还是window.location.pathname对象都会有这些信息。但有人可以确认或否认这一点。

+0

没有。 window.location.href将返回完整的url,包括查询字符串,例如http://domain.com/test.php?param=1&req=1而window.location。路径将仅返回路径如test.php的:) – Woppi 2012-10-31 02:10:31

5

使用window.location来读取和写入与当前帧相关的location object。如果您只想将地址设置为只读字符串,则可以使用document.URL,该值应与window.location.href的值相同。

2
document.location.href 

window.location.href