Inspeccionar enlaces externos con JavaScript: URLs, atributos rel y límites del DOM
Transparencia: este artículo se ha preparado con ayuda de IA para la redacción y los ejemplos. El código de clasificación se ha comprobado con casos sintéticos; no es una auditoría de sitios de terceros. Al revisar enlaces conviene separar dos preguntas: «¿a dónde enlaza este documento?» y «¿qué documentos de Internet enlazan a mi dominio?». JavaScript en la página puede ayudar con la primera. La…
1. External links: The distinction between internal and external links depends on the hostname. For example, blog.example.com is external to www.example.com. A different port with the same hostname is not considered external. We do not remove www or calculate the registrable domain. Grouping subdomains would require a different policy and a list of public suffixes. Simply checking if the href contains the domain name leads to false positives, such as example.com.evil.test and evil.test/?next=example.com.
2. Resolving URLs and preserving attributes: The function takes the base resolution and comparison hostname as separate arguments. A base href can change the destination of a relative link, but it should not change what page we are inspecting. The function checks if the URL is valid and if it uses http or https protocols. If the URL's hostname matches the page hostname, the link is ignored. The function also extracts rel attributes, such as nofollow, sponsored, and ugc, and stores them as separate boolean values.
3. Capturing a snapshot of the document: This part utilizes the previous function to collect records of external links. It queries all anchor tags with href attributes, applies the externalLinkRecord function to each one, and filters out any null results. The results are then grouped by hostname, with each group containing an array of records and the count of unique URLs.
4. Testing with small examples: The example domain is https://example.com/docs/, and the hostname is example.com. The expected results are provided for a few test cases, demonstrating the functionality of the code.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.