2009-06-22 63 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