Repository navigation
URL objects #497
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
URL objects #497
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
| @@ -1,28 +1,28 @@ | ||||||
|
|
||||||
| # URL objects | ||||||
|
|
||||||
| The built-in [URL](https://url.spec.whatwg.org/#api) class provides a convenient interface for creating and parsing URLs. | ||||||
| A classe nativa [URL](https://url.spec.whatwg.org/#api) fornece uma interface conveniente para criar e analisar URLs. | ||||||
|
|
||||||
| There are no networking methods that require exactly a `URL` object, strings are good enough. So technically we don't have to use `URL`. But sometimes it can be really helpful. | ||||||
| Não existem métodos de rede que exijam exatamente um objeto `URL`, strings são boas o suficiente. Então, tecnicamente, não precisamos usar `URL`. Mas às vezes isso pode ser muito útil. | ||||||
|
|
||||||
| ## Creating a URL | ||||||
| ## Criando uma URL | ||||||
|
|
||||||
| The syntax to create a new `URL` object: | ||||||
| A sintaxe para criar um novo objeto `URL`: | ||||||
|
|
||||||
| ```js | ||||||
| new URL(url, [base]) | ||||||
| ``` | ||||||
|
|
||||||
| - **`url`** -- the full URL or only path (if base is set, see below), | ||||||
| - **`base`** -- an optional base URL: if set and `url` argument has only path, then the URL is generated relative to `base`. | ||||||
| - **`url`** -- a URL completa ou só o caminho (se base estiver definido, veja abaixo), | ||||||
| - **`base`** -- uma URL base opcional: se definida e o argumento `url` tiver só o caminho, então a URL é gerada em relação a `base`. | ||||||
|
|
||||||
| For example: | ||||||
| Por exemplo: | ||||||
|
|
||||||
| ```js | ||||||
| let url = new URL('https://javascript.info/profile/admin'); | ||||||
| ``` | ||||||
|
|
||||||
| These two URLs are same: | ||||||
| Estas duas URLs são iguais: | ||||||
|
|
||||||
| ```js run | ||||||
| let url1 = new URL('https://javascript.info/profile/admin'); | ||||||
|
|
@@ -32,7 +32,7 @@ alert(url1); // https://javascript.info/profile/admin | |||||
| alert(url2); // https://javascript.info/profile/admin | ||||||
| ``` | ||||||
|
|
||||||
| We can easily create a new URL based on the path relative to an existing URL: | ||||||
| Podemos facilmente criar uma nova URL baseada no caminho relativo a uma URL existente: | ||||||
|
|
||||||
| ```js run | ||||||
| let url = new URL('https://javascript.info/profile/admin'); | ||||||
|
|
@@ -41,7 +41,7 @@ let newUrl = new URL('tester', url); | |||||
| alert(newUrl); // https://javascript.info/profile/tester | ||||||
| ``` | ||||||
|
|
||||||
| The `URL` object immediately allows us to access its components, so it's a nice way to parse the url, e.g.: | ||||||
| O objeto `URL` imediatamente nos permite acessar seus componentes, então é uma boa forma de analisar a url, por exemplo: | ||||||
|
|
||||||
| ```js run | ||||||
| let url = new URL('https://javascript.info/url'); | ||||||
|
|
@@ -51,130 +51,130 @@ alert(url.host); // javascript.info | |||||
| alert(url.pathname); // /url | ||||||
| ``` | ||||||
|
|
||||||
| Here's the cheatsheet for URL components: | ||||||
| Aqui está a cola de referência para os componentes da URL: | ||||||
|
|
||||||
|  | ||||||
|
|
||||||
| - `href` is the full url, same as `url.toString()` | ||||||
| - `protocol` ends with the colon character `:` | ||||||
| - `search` - a string of parameters, starts with the question mark `?` | ||||||
| - `hash` starts with the hash character `#` | ||||||
| - there may be also `user` and `password` properties if HTTP authentication is present: `http://login:password@site.com` (not painted above, rarely used). | ||||||
| - `href` é a url completa, igual a `url.toString()` | ||||||
| - `protocol` termina com o caractere de dois-pontos `:` | ||||||
| - `search` - uma string de parâmetros, começa com o ponto de interrogação `?` | ||||||
| - `hash` começa com o caractere de hash `#` | ||||||
| - também pode haver propriedades `user` e `password` se houver autenticação HTTP presente: `http://login:password@site.com` (não representado acima, raramente usado). | ||||||
|
|
||||||
|
|
||||||
| ```smart header="We can pass `URL` objects to networking (and most other) methods instead of a string" | ||||||
| We can use a `URL` object in `fetch` or `XMLHttpRequest`, almost everywhere where a URL-string is expected. | ||||||
| ```smart header="Podemos passar objetos `URL` para métodos de rede (e a maioria dos outros) em vez de uma string" | ||||||
| Podemos usar um objeto `URL` em `fetch` ou `XMLHttpRequest`, quase em todo lugar onde uma string de URL é esperada. | ||||||
|
|
||||||
| Generally, the `URL` object can be passed to any method instead of a string, as most methods will perform the string conversion, that turns a `URL` object into a string with full URL. | ||||||
| Em geral, o objeto `URL` pode ser passado para qualquer método em vez de uma string, já que a maioria dos métodos vai realizar a conversão de string, que transforma um objeto `URL` numa string com a URL completa. | ||||||
| ``` | ||||||
|
|
||||||
| ## SearchParams "?..." | ||||||
|
|
||||||
| Let's say we want to create a url with given search params, for instance, `https://google.com/search?query=JavaScript`. | ||||||
| Digamos que queremos criar uma url com parâmetros de busca dados, por exemplo, `https://google.com/search?query=JavaScript`. | ||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Opcional: "parâmetros de busca dados" ficou bem literal ("given search params") e pode ser lido como "parâmetros de dados". Que tal:
Suggested change
|
||||||
|
|
||||||
| We can provide them in the URL string: | ||||||
| Podemos fornecê-los na string da URL: | ||||||
|
|
||||||
| ```js | ||||||
| new URL('https://google.com/search?query=JavaScript') | ||||||
| ``` | ||||||
|
|
||||||
| ...But parameters need to be encoded if they contain spaces, non-latin letters, etc (more about that below). | ||||||
| ...Mas os parâmetros precisam ser codificados se contiverem espaços, letras não latinas, etc (mais sobre isso abaixo). | ||||||
|
|
||||||
| So there's a URL property for that: `url.searchParams`, an object of type [URLSearchParams](https://url.spec.whatwg.org/#urlsearchparams). | ||||||
| Então existe uma propriedade de URL para isso: `url.searchParams`, um objeto do tipo [URLSearchParams](https://url.spec.whatwg.org/#urlsearchparams). | ||||||
|
|
||||||
| It provides convenient methods for search parameters: | ||||||
| Ele fornece métodos convenientes para parâmetros de busca: | ||||||
|
|
||||||
| - **`append(name, value)`** -- add the parameter by `name`, | ||||||
| - **`delete(name)`** -- remove the parameter by `name`, | ||||||
| - **`get(name)`** -- get the parameter by `name`, | ||||||
| - **`getAll(name)`** -- get all parameters with the same `name` (that's possible, e.g. `?user=John&user=Pete`), | ||||||
| - **`has(name)`** -- check for the existence of the parameter by `name`, | ||||||
| - **`set(name, value)`** -- set/replace the parameter, | ||||||
| - **`sort()`** -- sort parameters by name, rarely needed, | ||||||
| - ...and it's also iterable, similar to `Map`. | ||||||
| - **`append(name, value)`** -- adiciona o parâmetro pelo `name`, | ||||||
| - **`delete(name)`** -- remove o parâmetro pelo `name`, | ||||||
| - **`get(name)`** -- obtém o parâmetro pelo `name`, | ||||||
| - **`getAll(name)`** -- obtém todos os parâmetros com o mesmo `name` (isso é possível, por exemplo, `?user=John&user=Pete`), | ||||||
| - **`has(name)`** -- checa a existência do parâmetro pelo `name`, | ||||||
| - **`set(name, value)`** -- define/substitui o parâmetro, | ||||||
| - **`sort()`** -- ordena os parâmetros por nome, raramente necessário, | ||||||
| - ...e também é iterável, parecido com `Map`. | ||||||
|
|
||||||
| An example with parameters that contain spaces and punctuation marks: | ||||||
| Um exemplo com parâmetros que contêm espaços e sinais de pontuação: | ||||||
|
|
||||||
| ```js run | ||||||
| let url = new URL('https://google.com/search'); | ||||||
|
|
||||||
| url.searchParams.set('q', 'test me!'); // added parameter with a space and ! | ||||||
| url.searchParams.set('q', 'test me!'); // parâmetro adicionado com um espaço e um ! | ||||||
|
|
||||||
| alert(url); // https://google.com/search?q=test+me%21 | ||||||
|
|
||||||
| url.searchParams.set('tbs', 'qdr:y'); // added parameter with a colon : | ||||||
| url.searchParams.set('tbs', 'qdr:y'); // parâmetro adicionado com dois-pontos : | ||||||
|
|
||||||
| // parameters are automatically encoded | ||||||
| // os parâmetros são codificados automaticamente | ||||||
| alert(url); // https://google.com/search?q=test+me%21&tbs=qdr%3Ay | ||||||
|
|
||||||
| // iterate over search parameters (decoded) | ||||||
| // itera sobre os parâmetros de busca (decodificados) | ||||||
| for(let [name, value] of url.searchParams) { | ||||||
| alert(`${name}=${value}`); // q=test me!, then tbs=qdr:y | ||||||
| alert(`${name}=${value}`); // q=test me!, depois tbs=qdr:y | ||||||
| } | ||||||
| ``` | ||||||
|
|
||||||
|
|
||||||
| ## Encoding | ||||||
| ## Codificação | ||||||
|
|
||||||
| There's a standard [RFC3986](https://tools.ietf.org/html/rfc3986) that defines which characters are allowed in URLs and which are not. | ||||||
| Existe um padrão, [RFC3986](https://tools.ietf.org/html/rfc3986), que define quais caracteres são permitidos em URLs e quais não são. | ||||||
|
|
||||||
| Those that are not allowed, must be encoded, for instance non-latin letters and spaces - replaced with their UTF-8 codes, prefixed by `%`, such as `%20` (a space can be encoded by `+`, for historical reasons, but that's an exception). | ||||||
| Aqueles que não são permitidos devem ser codificados, por exemplo, letras não latinas e espaços - substituídos pelos seus códigos UTF-8, prefixados por `%`, como `%20` (um espaço pode ser codificado por `+`, por motivos históricos, mas isso é uma exceção). | ||||||
|
|
||||||
| The good news is that `URL` objects handle all that automatically. We just supply all parameters unencoded, and then convert the `URL` to string: | ||||||
| A boa notícia é que objetos `URL` cuidam de tudo isso automaticamente. Só fornecemos todos os parâmetros sem codificação, e então convertemos a `URL` para string: | ||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Opcional: no original, "We just supply" tem o sentido de "basta fornecer", mas "Só fornecemos" pode ser lido como "fornecemos apenas". Além disso, o trecho fala do objeto, então "o objeto
Suggested change
|
||||||
|
|
||||||
| ```js run | ||||||
| // using some cyrillic characters for this example | ||||||
| // usando alguns caracteres cirílicos neste exemplo | ||||||
|
|
||||||
| let url = new URL('https://ru.wikipedia.org/wiki/Тест'); | ||||||
|
|
||||||
| url.searchParams.set('key', 'ъ'); | ||||||
| alert(url); //https://ru.wikipedia.org/wiki/%D0%A2%D0%B5%D1%81%D1%82?key=%D1%8A | ||||||
| ``` | ||||||
|
|
||||||
| As you can see, both `Тест` in the url path and `ъ` in the parameter are encoded. | ||||||
| Como você pode ver, tanto `Тест` no caminho da url quanto `ъ` no parâmetro são codificados. | ||||||
|
|
||||||
| The URL became longer, because each cyrillic letter is represented with two bytes in UTF-8, so there are two `%..` entities. | ||||||
| A URL ficou mais longa, porque cada letra cirílica é representada com dois bytes em UTF-8, então existem duas entidades `%..`. | ||||||
|
|
||||||
| ### Encoding strings | ||||||
| ### Codificando strings | ||||||
|
|
||||||
| In old times, before `URL` objects appeared, people used strings for URLs. | ||||||
| Nos tempos antigos, antes dos objetos `URL` aparecerem, as pessoas usavam strings para URLs. | ||||||
|
|
||||||
| As of now, `URL` objects are often more convenient, but strings can still be used as well. In many cases using a string makes the code shorter. | ||||||
| Hoje em dia, objetos `URL` costumam ser mais convenientes, mas strings ainda podem ser usadas também. Em muitos casos, usar uma string deixa o código mais curto. | ||||||
|
|
||||||
| If we use a string though, we need to encode/decode special characters manually. | ||||||
| Se usarmos uma string, porém, precisamos codificar/decodificar caracteres especiais manualmente. | ||||||
|
|
||||||
| There are built-in functions for that: | ||||||
| Existem funções nativas para isso: | ||||||
|
|
||||||
| - [encodeURI](mdn:/JavaScript/Reference/Global_Objects/encodeURI) - encodes URL as a whole. | ||||||
| - [decodeURI](mdn:/JavaScript/Reference/Global_Objects/decodeURI) - decodes it back. | ||||||
| - [encodeURIComponent](mdn:/JavaScript/Reference/Global_Objects/encodeURIComponent) - encodes a URL component, such as a search parameter, or a hash, or a pathname. | ||||||
| - [decodeURIComponent](mdn:/JavaScript/Reference/Global_Objects/decodeURIComponent) - decodes it back. | ||||||
| - [encodeURI](mdn:/JavaScript/Reference/Global_Objects/encodeURI) - codifica a URL como um todo. | ||||||
| - [decodeURI](mdn:/JavaScript/Reference/Global_Objects/decodeURI) - decodifica de volta. | ||||||
| - [encodeURIComponent](mdn:/JavaScript/Reference/Global_Objects/encodeURIComponent) - codifica um componente de URL, como um parâmetro de busca, ou um hash, ou um pathname. | ||||||
| - [decodeURIComponent](mdn:/JavaScript/Reference/Global_Objects/decodeURIComponent) - decodifica de volta. | ||||||
|
|
||||||
| A natural question is: "What's the difference between `encodeURIComponent` and `encodeURI`? When we should use either?" | ||||||
| Uma pergunta natural é: "Qual é a diferença entre `encodeURIComponent` e `encodeURI`? Quando devemos usar cada um?" | ||||||
|
|
||||||
| That's easy to understand if we look at the URL, that's split into components in the picture above: | ||||||
| Isso é fácil de entender se olharmos para a URL, dividida em componentes na imagem acima: | ||||||
|
|
||||||
| ``` | ||||||
| https://site.com:8080/path/page?p1=v1&p2=v2#hash | ||||||
| ``` | ||||||
|
|
||||||
| As we can see, characters such as `:`, `?`, `=`, `&`, `#` are allowed in URL. | ||||||
| Como podemos ver, caracteres como `:`, `?`, `=`, `&`, `#` são permitidos na URL. | ||||||
|
|
||||||
| ...On the other hand, if we look at a single URL component, such as a search parameter, these characters must be encoded, not to break the formatting. | ||||||
| ...Por outro lado, se olharmos para um único componente da URL, como um parâmetro de busca, esses caracteres precisam ser codificados, para não quebrar a formatação. | ||||||
|
|
||||||
| - `encodeURI` encodes only characters that are totally forbidden in URL. | ||||||
| - `encodeURIComponent` encodes same characters, and, in addition to them, characters `#`, `$`, `&`, `+`, `,`, `/`, `:`, `;`, `=`, `?` and `@`. | ||||||
| - `encodeURI` codifica só os caracteres que são totalmente proibidos na URL. | ||||||
| - `encodeURIComponent` codifica os mesmos caracteres, e, além deles, os caracteres `#`, `$`, `&`, `+`, `,`, `/`, `:`, `;`, `=`, `?` e `@`. | ||||||
|
|
||||||
| So, for a whole URL we can use `encodeURI`: | ||||||
| Então, para uma URL inteira podemos usar `encodeURI`: | ||||||
|
|
||||||
| ```js run | ||||||
| // using cyrillic characters in url path | ||||||
| // usando caracteres cirílicos no caminho da url | ||||||
| let url = encodeURI('http://site.com/привет'); | ||||||
|
|
||||||
| alert(url); // http://site.com/%D0%BF%D1%80%D0%B8%D0%B2%D0%B5%D1%82 | ||||||
| ``` | ||||||
|
|
||||||
| ...While for URL parameters we should use `encodeURIComponent` instead: | ||||||
| ...Enquanto para parâmetros de URL devemos usar `encodeURIComponent`: | ||||||
|
|
||||||
| ```js run | ||||||
| let music = encodeURIComponent('Rock&Roll'); | ||||||
|
|
@@ -183,7 +183,7 @@ let url = `https://google.com/search?q=${music}`; | |||||
| alert(url); // https://google.com/search?q=Rock%26Roll | ||||||
| ``` | ||||||
|
|
||||||
| Compare it with `encodeURI`: | ||||||
| Compare com `encodeURI`: | ||||||
|
|
||||||
| ```js run | ||||||
| let music = encodeURI('Rock&Roll'); | ||||||
|
|
@@ -192,26 +192,26 @@ let url = `https://google.com/search?q=${music}`; | |||||
| alert(url); // https://google.com/search?q=Rock&Roll | ||||||
| ``` | ||||||
|
|
||||||
| As we can see, `encodeURI` does not encode `&`, as this is a legit character in URL as a whole. | ||||||
| Como podemos ver, `encodeURI` não codifica `&`, já que esse é um caractere legítimo na URL como um todo. | ||||||
|
|
||||||
| But we should encode `&` inside a search parameter, otherwise, we get `q=Rock&Roll` - that is actually `q=Rock` plus some obscure parameter `Roll`. Not as intended. | ||||||
| Mas devemos codificar `&` dentro de um parâmetro de busca, caso contrário, obtemos `q=Rock&Roll` - que é na verdade `q=Rock` mais algum parâmetro obscuro `Roll`. Não como pretendido. | ||||||
|
|
||||||
| So we should use only `encodeURIComponent` for each search parameter, to correctly insert it in the URL string. The safest is to encode both name and value, unless we're absolutely sure that it has only allowed characters. | ||||||
| Então devemos usar só `encodeURIComponent` para cada parâmetro de busca, para inseri-lo corretamente na string da URL. O mais seguro é codificar tanto o nome quanto o valor, a menos que tenhamos absoluta certeza de que ele tem só caracteres permitidos. | ||||||
|
|
||||||
| ````smart header="Encoding difference compared to `URL`" | ||||||
| Classes [URL](https://url.spec.whatwg.org/#url-class) and [URLSearchParams](https://url.spec.whatwg.org/#interface-urlsearchparams) are based on the latest URI specification: [RFC3986](https://tools.ietf.org/html/rfc3986), while `encode*` functions are based on the obsolete version [RFC2396](https://www.ietf.org/rfc/rfc2396.txt). | ||||||
| ````smart header="Diferença de codificação comparada a `URL`" | ||||||
| As classes [URL](https://url.spec.whatwg.org/#url-class) e [URLSearchParams](https://url.spec.whatwg.org/#interface-urlsearchparams) são baseadas na especificação URI mais recente: [RFC3986](https://tools.ietf.org/html/rfc3986), enquanto as funções `encode*` são baseadas na versão obsoleta [RFC2396](https://www.ietf.org/rfc/rfc2396.txt). | ||||||
|
|
||||||
| There are a few differences, e.g. IPv6 addresses are encoded differently: | ||||||
| Existem algumas diferenças, por exemplo, endereços IPv6 são codificados de forma diferente: | ||||||
|
|
||||||
| ```js run | ||||||
| // valid url with IPv6 address | ||||||
| // url válida com endereço IPv6 | ||||||
| let url = 'http://[2607:f8b0:4005:802::1007]/'; | ||||||
|
|
||||||
| alert(encodeURI(url)); // http://%5B2607:f8b0:4005:802::1007%5D/ | ||||||
| alert(new URL(url)); // http://[2607:f8b0:4005:802::1007]/ | ||||||
| ``` | ||||||
|
|
||||||
| As we can see, `encodeURI` replaced square brackets `[...]`, that's not correct, the reason is: IPv6 urls did not exist at the time of RFC2396 (August 1998). | ||||||
| Como podemos ver, `encodeURI` substituiu os colchetes `[...]`, o que não está correto, a razão é: urls IPv6 não existiam na época do RFC2396 (agosto de 1998). | ||||||
|
|
||||||
| Such cases are rare, `encode*` functions work well most of the time. | ||||||
| Esses casos são raros, as funções `encode*` funcionam bem na maior parte do tempo. | ||||||
| ```` | ||||||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Importante: o título do artigo ficou sem tradução. Nos artigos já traduzidos o título também é traduzido (por exemplo,
# Objetosem1-js/04-object-basics/01-object/article.md). Sugestão: