js怎么准确获取当前页面url网址

在JavaScript中,获取当前页面的URL网址有多种方法,以下是一些常用的方法:

1、使用window.location.href属性

js怎么准确获取当前页面url网址

这是最常用的方法,可以直接通过window.location.href属性获取当前页面的完整URL。

var currentUrl = window.location.href;
console.log(currentUrl);

2、使用window.location.protocolwindow.location.hostwindow.location.pathname属性

如果你只需要获取协议、主机名和路径名部分,可以使用这些属性组合起来。

var protocol = window.location.protocol;
var host = window.location.host;
var pathname = window.location.pathname;
var currentUrl = protocol + "//" + host + pathname;
console.log(currentUrl);

3、使用document.referrer属性

document.referrer属性可以获取当前页面是从哪个页面跳转过来的。

js怎么准确获取当前页面url网址

var referrer = document.referrer;
console.log(referrer);

4、使用history.pushState()history.replaceState()方法

这两个方法可以用来修改浏览器的历史记录,同时也可以获取到修改后的URL。

history.pushState({}, '', 'new-url');
var newUrl = history.state && history.state.newUrl;
console.log(newUrl); // new-url

5、使用HTML5的history.pushState()history.replaceState()方法(兼容旧版浏览器)

这两个方法也可以用来修改浏览器的历史记录,同时也可以获取到修改后的URL。

history.pushState({}, '', 'new-url');
var newUrl = document.referrer; // new-url
console.log(newUrl);

6、使用事件监听器(如点击事件)获取URL

js怎么准确获取当前页面url网址

你可以通过监听用户的操作(如点击链接或按钮)来获取URL。

document.querySelector('a').addEventListener('click', function(event) {
  event.preventDefault(); // 阻止默认行为,避免页面跳转
  var targetUrl = event.target.href; // 获取目标URL
  console.log(targetUrl); // http://example.com/new-page/
});

7、使用第三方库(如jQuery)获取URL

如果你的项目使用了jQuery库,可以使用其提供的$.ajaxSetup()方法来获取URL。

$.ajaxSetup({
  url: window.location.href // 设置请求的URL为当前页面的URL
});

以上就是在JavaScript中获取当前页面URL的一些常用方法,需要注意的是,不同的方法可能在不同的浏览器和环境中有不同的表现,因此在实际应用中需要根据具体需求选择合适的方法。

原创文章,作者:K-seo,如若转载,请注明出处:https://www.kdun.cn/ask/237773.html

(0)
K-seoK-seoSEO优化员
上一篇 2024年1月21日 03:52
下一篇 2024年1月21日 03:56

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

免备案 高防CDN 无视CC/DDOS攻击 限时秒杀,10元即可体验  (专业解决各类攻击)>>点击进入