想要获取、设置浏览器地址栏 URL,window.location的这些干活必须掌握

window.location 是 JavaScript 中用于获取和设置浏览器地址栏 URL 的对象,能够进行页面跳转、获取当前 URL、重新加载页面等操作。它是 window 对象的一部分,提供了多种属性和方法来操作 URL 和浏览器行为。

  1. window.location.href
    作用:返回当前页面的完整 URL,跳转自定义地址
    // 获取当前页面的 URL
    console.log(window.location.href); // https://xxx/page?pageId=1
    
    // 设置新的 URL,跳转到百度
    window.location.href = 'https://www.baidu.com/index.htm';
  2. window.location.hostname
    作用:获取当前 URL 的主机名(不包括协议、端口和路径)
    //https://www.baidu.com/index.htm
    console.log(window.location.hostname)  // www.baidu.com
  3.  window.location.protocol
    作用:获取当前 URL 的协议部分(如 http:https:
    //https://www.baidu.com/index.htm
    console.log(window.location.protocol); // https:
  4. window.location.port
    作用:获取当前 URL 的端口号。如果没有指定端口,返回空字符串

    console.log(window.location.port); // 8080 (如果 URL 中指定了端口号)
  5. window.location.pathname
    作用:获取当前 URL 的路径部分,不包括域名和查询参数
    //https://www.baidu.com/index.htm
    console.log(window.location.pathname); // /index.htm
  6.  window.location.pathname
    作用:获取当前 URL 的路径部分,不包括域名和查询参数
    //https://www.baidu.com/index.htm
    console.log(window.location.pathname); // /index.htm
  7. window.location.search
    作用:获取当前 URL 的查询字符串部分(即 ? 后面的部分,包括查询参数)
    // https://xxx/page?pageId=1
    console.log(window.location.search); // ?pageId=1
  8.  window.location.search
    作用:获取当前 URL 的查询字符串部分(即 ? 后面的部分,包括查询参数)
    // https://xxx/page?pageId=1
    console.log(window.location.search); // ?pageId=1
  9. window.location.hash
    作用:获取或设置当前 URL 的锚点部分(即 # 后面的部分),用于页面内导航
    // https://xxx/page#section1
    console.log(window.location.hash); // #section1
  10.  window.location.replace

    作用:跳转到指定 URL,但不会在历史记录中添加当前页面。这意味着用户无法使用浏览器的后退按钮返回到当前页面

    window.location.replace('https://www.baidu.com/index.htm')
  11.  window.location.reload

    作用:刷新当前页面。如果传递 true,则会强制从服务器重新加载页面(不使用缓存);否则,默认会使用缓存

    window.location.reload(); // 重新加载页面,使用缓存
    window.location.reload(true); // 强制重新加载页面,不使用缓存
  12. window.location.origin

    作用:获取当前页面的根域名部分(包括协议、主机名和端口)。它相当于将 protocol + hostname + port 拼接在一起

    // https://www.xxx.com:8080
    console.log(window.location.origin); // https://www.xxx.com:8080

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值