Como ler a URL, o domínio e o caminho com location em JavaScript

Use window.location.href para ler o endereço atual, window.location.hostname para o nome do host e window.location.pathname para o caminho. O objeto Location está vinculado à URL do documento atual. Para analisar outro endereço, use new URL(address).

Ler as partes da URL atual

A tabela divide o endereço de exemplo https://example.com:8080/path/page.html?lang=ko&tag=js&tag=dom&q=hello+world#part. host inclui a porta quando ela foge do padrão, enquanto hostname a omite. Se a porta faltar ou for a padrão do HTTPS, 443, port é uma string vazia. Veja as definições em HTML Living Standard.

Propriedade Valor de exemplo Significado
href https://example.com:8080/path/page.html?lang=ko&tag=js&tag=dom&q=hello+world#part URL completa
origin https://example.com:8080 Esquema HTTP(S), nome do host e porta
protocol https: Esquema com dois-pontos no fim
host example.com:8080 Nome do host e porta não padrão
hostname example.com Nome do host sem a porta
port 8080 Número de porta não padrão
pathname /path/page.html Caminho sem consulta nem fragmento
search ?lang=ko&tag=js&tag=dom&q=hello+world Consulta com o ponto de interrogação
hash #part Fragmento com o sinal de cerquilha

Analisar endereços e parâmetros de consulta

Execute o trecho no console do navegador. As duas primeiras linhas exibem o endereço e o caminho do documento atual. As demais mostram as partes do exemplo. new URL() analisa o endereço sem enviar solicitações de rede nem mudar de página.

const current = window.location;
console.log(current.href);
console.log(current.pathname);

const sample = new URL('https://example.com:8080/path/page.html?lang=ko&tag=js&tag=dom&q=hello+world#part');
console.log(sample.host);
console.log(sample.hostname);
console.log(sample.searchParams.get('lang'));   // ko
console.log(sample.searchParams.get('tag'));    // js
console.log(sample.searchParams.getAll('tag')); // ['js', 'dom']
console.log(sample.searchParams.get('q'));      // hello world

search contém a consulta com o ?. searchParams.get('tag') retorna o primeiro valor, js, e getAll('tag') retorna ['js', 'dom'] em ordem. Quando a chave não existe, get() retorna null e getAll() retorna um array vazio. Com tag=, o valor é uma string vazia. + é decodificado como espaço, então q vale hello world. Consulte URL Standard.

Exemplo completo: comparar a URL atual com a digitada

Salve o HTML em UTF-8 como location-example.html e abra no navegador. Analisar URL lê o endereço absoluto no campo. URL desta página copia e analisa o endereço do documento aberto. Restaurar recupera o exemplo.

<!doctype html>
<html lang="pt">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Examinar as partes de uma URL</title>
</head>
<body>
<label for="address">URL absoluta para examinar</label>
<input id="address" type="url" size="60" value="https://example.com:8080/path/page.html?lang=ko&amp;tag=js&amp;tag=dom&amp;q=hello+world#part">
<button id="parse" type="button">Analisar URL</button>
<button id="current" type="button">URL desta página</button>
<button id="reset" type="button">Restaurar</button>
<pre id="output" aria-live="polite"></pre>
<script>
const address = document.querySelector('#address');
const output = document.querySelector('#output');

function show(value) {
  try {
    const url = new URL(value);
    output.textContent = [
      `href: ${url.href}`,
      `origin: ${url.origin}`,
      `protocol: ${url.protocol}`,
      `host: ${url.host}`,
      `hostname: ${url.hostname}`,
      `port: ${url.port || "(ausente)"}`,
      `pathname: ${url.pathname}`,
      `search: ${url.search || "(ausente)"}`,
      `hash: ${url.hash || "(ausente)"}`,
      `lang: ${url.searchParams.get('lang') ?? "(ausente)"}`,
      `tag: ${JSON.stringify(url.searchParams.getAll('tag'))}`,
      `q: ${url.searchParams.get('q') ?? "(ausente)"}`,
    ].join('\n');
  } catch (error) {
    output.textContent = "Digite uma URL absoluta válida.";
  }
}

document.querySelector('#parse').addEventListener('click', () => show(address.value));
document.querySelector('#current').addEventListener('click', () => {
  address.value = window.location.href;
  show(address.value);
});
document.querySelector('#reset').addEventListener('click', () => {
  address.value = 'https://example.com:8080/path/page.html?lang=ko&tag=js&tag=dom&q=hello+world#part';
  show(address.value);
});
show(address.value);
</script>
</body>
</html>

Na saída inicial, host inclui :8080 e hostname o omite. O array tag mostra os dois valores e q contém um espaço. Digitar só /path/page.html gera um erro porque falta uma base. Para resolver caminhos relativos, use new URL(relativePath, baseURL). Se abrir o arquivo no disco, o endereço atual começa com file:.

Ler um endereço ou navegar até ele

Atribuir a location.href ou chamar location.assign(url) inicia uma navegação. location.replace(url) também substitui a entrada atual do histórico, então Voltar pula a página substituída. O exemplo apenas mostra propriedades. Antes de navegar, confirme se o esquema e a origem são permitidos pelo projeto. Veja HTML Living Standard.