我只想获取网站URL。不是从链接获取的URL。在页面加载时,我需要能够获取网站的完整、当前URL,并将其设置为一个变量,以便根据需要进行处理。
当前回答
获取当前位置对象的方法是window.location。
将其与document.location进行比较,后者最初仅以字符串形式返回当前URL。可能是为了避免混淆,document.location被document.URL替换。
而且,所有现代浏览器都会将document.location映射到window.location。
实际上,为了跨浏览器安全,应该使用window.location而不是document.location。
其他回答
Use:
window.location.href
正如评论中所指出的,下面这行行是有效的,但它对Firefox来说是错误的。
document.URL
请参阅DOMString类型的URL,只读。
对于带有查询字符串的完整URL:
document.location.toString()
对于主机URL:
window.location
var currentPageUrlIs = "";
if (typeof this.href != "undefined") {
currentPageUrlIs = this.href.toString().toLowerCase();
}else{
currentPageUrlIs = document.location.toString().toLowerCase();
}
以上代码也可以帮助某人
您可以通过location.href获取当前页面的完整链接要获取当前控制器的链接,请使用:
location.href.substring(0, location.href.lastIndexOf('/'));
您可以使用以下方法获取带有哈希标记的当前URL位置:
JavaScript:
// Using href
var URL = window.location.href;
// Using path
var URL = window.location.pathname;
jQuery:
$(location).attr('href');
推荐文章
- 如何为Firebase构建云函数,以便从多个文件部署多个函数?
- 如何发送推送通知到web浏览器?
- AngularJS:工厂和服务?
- js:将一个组件包装成另一个组件
- 父ng-repeat从子ng-repeat的访问索引
- JSHint和jQuery: '$'没有定义
- 模仿JavaScript中的集合?
- 用JavaScript验证电话号码
- 如何在HTML5中改变视频的播放速度?
- 谷歌地图API v3:我可以setZoom后fitBounds?
- ES6/2015中的null安全属性访问(和条件赋值)
- 与push()相反;
- JS字符串“+”vs concat方法
- AngularJS使用ng-class切换类
- 访问Handlebars.js每次循环范围之外的变量