我只想获取网站URL。不是从链接获取的URL。在页面加载时,我需要能够获取网站的完整、当前URL,并将其设置为一个变量,以便根据需要进行处理。
当前回答
Nikhil Agrawal的回答很好,只是在这里添加了一个小示例,您可以在控制台中看到不同的组件:
如果您想要不带路径或查询参数的基本URL(例如,对其执行AJAX请求以在开发/登台和生产服务器上运行),window.location.origin是最好的,因为它保留了协议和可选端口(在Django开发中,有时会有一个非标准端口,如果您只使用主机名等,就会中断它)
其他回答
获取当前页面URL:
window.location.href
对于带有查询字符串的完整URL:
document.location.toString()
对于主机URL:
window.location
您可以使用以下方法获取带有哈希标记的当前URL位置:
JavaScript:
// Using href
var URL = window.location.href;
// Using path
var URL = window.location.pathname;
jQuery:
$(location).attr('href');
添加结果以供快速参考
窗口位置;
Location {href: "https://stackoverflow.com/questions/1034621/get-the-current-url-with-javascript",
ancestorOrigins: DOMStringList,
origin: "https://stackoverflow.com",
replace: ƒ, assign: ƒ, …}
文档位置
Location {href: "https://stackoverflow.com/questions/1034621/get-the-current-url-with-javascript",
ancestorOrigins: DOMStringList,
origin: "https://stackoverflow.com",
replace: ƒ, assign: ƒ
, …}
窗口位置路径名
"/questions/1034621/get-the-current-url-with-javascript"
窗口.location.href
"https://stackoverflow.com/questions/1034621/get-the-current-url-with-javascript"
位置主机名
"stackoverflow.com"
Use:
window.location.href
正如评论中所指出的,下面这行行是有效的,但它对Firefox来说是错误的。
document.URL
请参阅DOMString类型的URL,只读。
推荐文章
- 一元加/数字(x)和parseFloat(x)之间的区别是什么?
- angularjs中的compile函数和link函数有什么区别
- 删除绑定中添加的事件监听器
- 很好的初学者教程socket.io?
- HtmlSpecialChars在JavaScript中等价于什么?
- React: 'Redirect'没有从' React -router-dom'中导出
- 如何在React中使用钩子强制组件重新渲染?
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法
- 如何以及为什么'a'['toUpperCase']()在JavaScript工作?
- 有Grunt生成index.html不同的设置
- 文档之间的区别。addEventListener和window。addEventListener?
- 如何检查动态附加的事件监听器是否存在?