我只想获取网站URL。不是从链接获取的URL。在页面加载时,我需要能够获取网站的完整、当前URL,并将其设置为一个变量,以便根据需要进行处理。


当前回答

首先检查页面是否完全加载到

browser,window.location.toString();

window.location.href

然后调用一个获取url、url变量并在控制台上打印的函数,

$(window).load(function(){
   var url = window.location.href.toString();
   var URL = document.URL;
   var wayThreeUsingJQuery = $(location).attr('href');
   console.log(url);
   console.log(URL);
   console.log(wayThreeUsingJQuery );
});

其他回答

Nikhil Agrawal的回答很好,只是在这里添加了一个小示例,您可以在控制台中看到不同的组件:

如果您想要不带路径或查询参数的基本URL(例如,对其执行AJAX请求以在开发/登台和生产服务器上运行),window.location.origin是最好的,因为它保留了协议和可选端口(在Django开发中,有时会有一个非标准端口,如果您只使用主机名等,就会中断它)

好的,使用纯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=“此页面的完整URL为:<br>”+window.location.href;<!DOCTYPE html><html><body><h2>JavaScript</h2><h3>窗口.location.href</h3><p id=“root”></p></body></html>

同样值得一提的是:

如果需要相对路径,只需使用window.location.pathname;如果要获取主机名,可以使用window.location.hostname;如果需要单独获取协议,请使用window.location.protocol此外,如果您的页面具有哈希标记,则可以获取如下内容:window.location.hash。

所以window.location.href一次处理所有内容。。。基本上:

window.location.protocol + '//' + window.location.hostname + window.location.pathname + window.location.hash === window.location.href;
    //true

如果已经在窗口范围内,则不需要使用窗口。。。

因此,在这种情况下,您可以使用:

location.protocol

location.hostname

location.pathname

location.hash

location.href

你有多种方法可以做到这一点。

1:

location.href;

2:

document.URL;

3:

document.documentURI;

首先检查页面是否完全加载到

browser,window.location.toString();

window.location.href

然后调用一个获取url、url变量并在控制台上打印的函数,

$(window).load(function(){
   var url = window.location.href.toString();
   var URL = document.URL;
   var wayThreeUsingJQuery = $(location).attr('href');
   console.log(url);
   console.log(URL);
   console.log(wayThreeUsingJQuery );
});

对于那些想要一个实际的URL对象的人,可能是一个以URL为参数的实用程序:

const url = new URL(window.location.href)

https://developer.mozilla.org/en-US/docs/Web/API/URL