Skip to content

Commit 08d3e29

Browse files
author
Simon Planinschek
committed
Added utilities functions for handling cookies and DOM verification
1 parent 9450f59 commit 08d3e29

1 file changed

Lines changed: 49 additions & 0 deletions

File tree

src/utilities.ts

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/**
2+
* Regex based filter to get cookie values
3+
* This includes the =
4+
*
5+
* @param name { string } - Filter keyword
6+
*/
7+
const getCookiePattern = (name: string): RegExp => RegExp(name + '=.[^;]*')
8+
9+
/**
10+
* Get cookie from document (Local DOM)
11+
*
12+
* @param name { string } - Cookie name
13+
*/
14+
function getCookieFromDocument(name: string): string | undefined {
15+
const pattern = getCookiePattern(name)
16+
const matched = document.cookie.match(pattern)
17+
18+
if (!matched) {
19+
return undefined
20+
}
21+
22+
const cookie = matched[0].split('=')
23+
return decodeURIComponent(cookie[1])
24+
}
25+
26+
/**
27+
* Set new cookie
28+
*
29+
* @param name { string } - Cookie name
30+
* @param value { string } - Cookie value
31+
*/
32+
function setCookie(name: string, value: string): void {
33+
document.cookie = name + '=' + value + ';path=/'
34+
}
35+
36+
/**
37+
* Check if the DOM is available
38+
* if this function returns false, it means that the page is not rendered by the client.
39+
* However, it might be pre-rendered for example on a server.
40+
*/
41+
function canUseDOM(): boolean {
42+
return !!(
43+
typeof window != 'undefined' &&
44+
window.document &&
45+
window.document.createElement
46+
)
47+
}
48+
49+
export { getCookieFromDocument, setCookie, canUseDOM }

0 commit comments

Comments
 (0)