我只想获取网站URL。不是从链接获取的URL。在页面加载时,我需要能够获取网站的完整、当前URL,并将其设置为一个变量,以便根据需要进行处理。
当前回答
使用:window.location.href。
如上所述,更新window.location时,document.URL不会更新。请参阅MDN。
其他回答
使用此项:
var url=window.location.href;console.log(url);
对于带有查询字符串的完整URL:
document.location.toString()
对于主机URL:
window.location
好的,使用纯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
您可以使用以下方法获取带有哈希标记的当前URL位置:
JavaScript:
// Using href
var URL = window.location.href;
// Using path
var URL = window.location.pathname;
jQuery:
$(location).attr('href');
URL信息访问
JavaScript为您提供了许多方法来检索和更改显示在浏览器地址栏中的当前URL。所有这些方法都使用Location对象,这是Window对象的属性。您可以通过读取window.Location来读取当前Location对象:
var currentLocation = window.location;
基本URL结构
<protocol>//<hostname>:<port>/<pathname><search><hash>
protocol:指定用于访问Internet上资源的协议名称。(HTTP(不带SSL)或HTTPS(带SSL))hostname:主机名指定拥有资源的主机。例如,www.stackeoverflow.com。服务器使用主机名提供服务。端口:用于识别Internet或其他网络消息到达服务器时要转发到的特定进程的端口号。路径名:路径提供有关Web客户端希望访问的主机内特定资源的信息。例如,/index.html。搜索:路径组件后面有一个查询字符串,它提供了资源可以用于某些目的的信息字符串(例如,作为搜索的参数或作为要处理的数据)。hash:URL的锚定部分,包括哈希符号(#)。
使用这些Location对象财产,您可以访问所有这些URL组件以及它们可以设置或返回的内容:
href-整个URLprotocol-URL的协议host—URL的主机名和端口hostname—URL的主机名port-服务器用于URL的端口号pathname—URL的路径名search-URL的查询部分hash-URL的锚定部分origin-window.location.protocol+'//'+window.location.host
我希望你得到了答案。。
推荐文章
- 在JavaScript中将JSON字符串解析为特定对象原型
- 将字符串“true”/“false”转换为布尔值
- 如何使用JavaScript代码获得浏览器宽度?
- event.preventDefault()函数在IE中无法工作
- indexOf()和search()的区别是什么?
- 错误:'types'只能在.ts文件中使用- Visual Studio Code使用@ts-check
- React-Native:应用程序未注册错误
- LoDash:从对象属性数组中获取值数组
- src和dist文件夹的作用是什么?
- jQuery UI对话框-缺少关闭图标
- 如何使用AngularJS获取url参数
- 将RGB转换为白色的RGBA
- 如何将“camelCase”转换为“Camel Case”?
- 我们可以在另一个JS文件中调用用一个JavaScript编写的函数吗?
- 如何使用JavaScript重新加载ReCaptcha ?