|
1 | | -function outboundLinkInBlank(clipboard) { |
2 | | - document.querySelectorAll('a').forEach(function (link) { |
3 | | - var href = link.getAttribute('href'); |
4 | | - if ( |
5 | | - href && |
6 | | - href.startsWith('http') && |
7 | | - (!href.startsWith('https://www.cloudwego.io') || !href.startsWith('https://www.cloudwego.cn')) |
8 | | - ) { |
9 | | - link.setAttribute('target', '_blank'); |
| 1 | +/** |
| 2 | + * Extracts the top-level domain from a given hostname. |
| 3 | + * |
| 4 | + * @param hostname - The full hostname string from which to extract the top-level domain. |
| 5 | + * @returns The top-level domain string, or the original hostname if it has two or fewer parts. |
| 6 | + */ |
| 7 | +function getTopLevelDomain(hostname) { |
| 8 | + if (hostname.startsWith("www.")) { |
| 9 | + hostname = hostname.substring(4); |
| 10 | + } |
| 11 | + |
| 12 | + const parts = hostname.split(".").filter(Boolean); |
| 13 | + if (parts.length > 2) { |
| 14 | + return parts.slice(-2).join("."); |
| 15 | + } else { |
| 16 | + return hostname; |
| 17 | + } |
| 18 | +} |
| 19 | + |
| 20 | +/** |
| 21 | + * Extracts the domain without subdomains from a given URL string. |
| 22 | + * |
| 23 | + * @param urlString - The URL string from which to extract the domain without subdomains. |
| 24 | + * @returns The domain without subdomains if the URL is valid, otherwise null. |
| 25 | + */ |
| 26 | +function getDomainWithoutSubdomains(urlString) { |
| 27 | + try { |
| 28 | + const url = new URL(urlString); |
| 29 | + return getTopLevelDomain(url.hostname); |
| 30 | + } catch (error) { |
| 31 | + console.error("Invalid URL:", error); |
| 32 | + return null; |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | +function outboundLinkInBlank() { |
| 37 | + const selfDomains = ["cloudwego.io", "cloudwego.cn"]; |
| 38 | + document.querySelectorAll("a").forEach(function (link) { |
| 39 | + const href = link.getAttribute("href"); |
| 40 | + if (href && href.startsWith("http")) { |
| 41 | + try { |
| 42 | + const url = new URL(href); |
| 43 | + const host = url.host; |
| 44 | + const domain = getDomainWithoutSubdomains(host); |
| 45 | + if (!selfDomains.includes(domain)) { |
| 46 | + link.setAttribute("target", "_blank"); |
| 47 | + } |
| 48 | + } catch (e) { |
| 49 | + console.error("Invalid URL:", href); |
| 50 | + } |
10 | 51 | } |
11 | 52 | }); |
12 | 53 | } |
|
0 commit comments