我想要的只是获取网站 URL。不是从链接中获取的 URL。在页面加载时,我需要能够获取网站的完整当前 URL 并将其设置为一个变量以随心所欲。
使用 JavaScript 获取当前 URL?
用:
window.location.href
正如评论中所指出的,下面的行有效,但它在 Firefox 中被窃听。
document.URL
URL 信息访问
JavaScript 为您提供了许多方法来检索和更改当前显示在浏览器地址栏中的 URL。所有这些方法都使用Location对象,它是对象的一个属性Window。您可以创建一个Location具有当前 URL的新对象,如下所示:
var currentLocation = window.location;
基本网址结构
<protocol>//<hostname>:<port>/<pathname><search><hash>
protocol:指定用于访问Internet 资源的协议名称。(HTTP(不带 SSL)或 HTTPS(带 SSL))
主机名:主机名指定拥有资源的主机。例如,
www.stackoverflow.com。服务器使用主机名提供服务。端口:用于识别特定进程的端口号,当 Internet 或其他网络消息到达服务器时将转发到该进程。
路径名:该路径提供有关 Web 客户端要访问的主机内特定资源的信息。例如,
/index.html。搜索:查询字符串跟在路径组件之后,并提供资源可用于某些目的的信息字符串(例如,作为搜索的参数或作为要处理的数据)。
hash: URL 的锚点部分,包括井号 (#)。
使用这些Location对象属性,您可以访问所有这些 URL 组件以及它们可以设置或返回的内容:
- href - 整个 URL
 - protocol - URL 的协议
 - host - URL 的主机名和端口
 - 主机名- URL 的主机名
 - port - 服务器用于 URL 的端口号
 - pathname - URL 的路径名
 - search - URL 的查询部分
 - hash - URL 的锚点部分
 
我希望你得到你的答案..
用于window.location对与当前帧关联的位置对象的读写访问。如果您只想将地址作为只读字符串获取,您可以使用document.URL,它应该包含与window.location.href.
获取当前页面 URL:
window.location.href
好的,使用纯 JavaScript 可以轻松获取当前页面的完整 URL。例如,在此页面上尝试此代码:
window.location.href;
// use it in the console of this page will return
// http://stackoverflow.com/questions/1034621/get-current-url-in-web-browser"
该
window.location.href属性返回当前页面的 URL。
document.getElementById("root").innerHTML = "The full URL of this page is:<br>" + window.location.href;
<!DOCTYPE html>
<html>
<body>
  <h2>JavaScript</h2>
  <h3>The window.location.href</h3>
  <p id="root"></p>
</body>
</html>
提到这些也不错:
如果您需要相对路径,只需使用
window.location.pathname;如果您想获取主机名,可以使用
window.location.hostname;如果您需要单独获取协议,请使用
window.location.protocol- 另外,如果你的页面有
hash标签,你可以得到它喜欢:window.location.hash。 
- 另外,如果你的页面有
 
所以window.location.href一次性全部处理......基本上:
window.location.protocol + '//' + window.location.hostname + window.location.pathname + window.location.hash === window.location.href;
    //true
window如果已经在窗口范围内,也不需要使用...
因此,在这种情况下,您可以使用:
location.protocol
location.hostname
location.pathname
location.hash
location.href
