我只想获取网站URL。不是从链接获取的URL。在页面加载时,我需要能够获取网站的完整、当前URL,并将其设置为一个变量,以便根据需要进行处理。
当前回答
获取当前位置对象的方法是window.location。
将其与document.location进行比较,后者最初仅以字符串形式返回当前URL。可能是为了避免混淆,document.location被document.URL替换。
而且,所有现代浏览器都会将document.location映射到window.location。
实际上,为了跨浏览器安全,应该使用window.location而不是document.location。
其他回答
对于带有查询字符串的完整URL:
document.location.toString()
对于主机URL:
window.location
let url=新url(window.location.href);console.log(url.href);
使用以上代码获取网站的当前URL。
或者试试这个https://bbbootstrap.com/code/get-current-url-javascript-54628697
使用:window.location.href。
如上所述,更新window.location时,document.URL不会更新。请参阅MDN。
首先检查页面是否完全加载到
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 );
});
你有多种方法可以做到这一点。
1:
location.href;
2:
document.URL;
3:
document.documentURI;