Узнать URL сайта с помощью js
Допустим скрипт заходит на страницу, и должен в консоль вывести URL. Как и с помощью чего это можно сделать? Спасибо.
Ответы (1 шт):
Автор решения: Станислав Усанов
→ Ссылка
export class UrlParser {
constructor(url) {
this.el = document.createElement('a');
this.el.href = url === undefined ? window.location.href : url;
this.href = this.el.href;
this.protocol = this.el.protocol;
this.hostname = this.el.hostname;
this.port = this.el.port;
this.pathname = this.el.pathname;
this.search = this.el.search;
this.hash = this.el.hash;
}
parsePathname() {
const result = this.pathname
.substr(1)
.split('/')
.filter(item => item.length > 0);
return result.length > 0 ? result : null;
}
parseSearch() {
const result = this.search
.substr(1)
.split('&')
.filter(item => item.length > 0);
if (result.length > 0) {
const obj = {};
result.forEach(element => {
const parse = element.split('=');
obj[parse[0]] = parse[1];
});
return obj;
} else {
return null;
}
}
}