forked from utags/userscripts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathurl.ts
More file actions
61 lines (54 loc) · 1.55 KB
/
Copy pathurl.ts
File metadata and controls
61 lines (54 loc) · 1.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import { win } from '../globals/win'
/**
* Extract the top-level domain from a URL or the current location
* @param url The URL to extract the domain from (optional, defaults to current location)
* @returns {string} The top-level domain
*/
export function extractDomain(url?: string): string {
try {
let hostname: string
if (url) {
try {
hostname = new URL(url).hostname
} catch {
hostname = url // Assume it's already a hostname if URL parsing fails
}
} else {
hostname = win.location.hostname
}
// Remove 'www.' if present
let domain = hostname.replace(/^www\./, '')
// Extract the top-level domain (e.g., example.com from sub.example.com)
const parts = domain.split('.')
if (parts.length > 2) {
// Handle special cases like co.uk, com.au, etc.
const secondLevelDomains = [
'co',
'com',
'org',
'net',
'edu',
'gov',
'mil',
]
const thirdLevelDomain = parts[parts.length - 2]
domain =
parts.length > 2 && secondLevelDomains.includes(thirdLevelDomain)
? parts.slice(-3).join('.')
: parts.slice(-2).join('.')
}
return domain
} catch {
return url || win.location.hostname || '' // Fallback
}
}
export function isSameOrigin(url: string, baseHref?: string): boolean {
try {
const base = baseHref ?? win.location.href
const target = new URL(url, base)
const baseUrl = new URL(base)
return target.origin === baseUrl.origin
} catch {
return false
}
}