| 89 | export type ClearCookieOptions = Omit<HttpCookie, 'key' | 'value'>; |
| 90 | |
| 91 | export class CapacitorCookiesPluginWeb extends WebPlugin implements CapacitorCookiesPlugin { |
| 92 | async getCookies(): Promise<HttpCookieMap> { |
| 93 | const cookies = document.cookie; |
| 94 | const cookieMap: HttpCookieMap = {}; |
| 95 | cookies.split(';').forEach((cookie) => { |
| 96 | if (cookie.length <= 0) return; |
| 97 | // Replace first "=" with CAP_COOKIE to prevent splitting on additional "=" |
| 98 | let [key, value] = cookie.replace(/=/, 'CAP_COOKIE').split('CAP_COOKIE'); |
| 99 | key = decode(key).trim(); |
| 100 | value = decode(value).trim(); |
| 101 | cookieMap[key] = value; |
| 102 | }); |
| 103 | return cookieMap; |
| 104 | } |
| 105 | |
| 106 | async setCookie(options: SetCookieOptions): Promise<void> { |
| 107 | try { |
| 108 | // Safely Encoded Key/Value |
| 109 | const encodedKey = encode(options.key); |
| 110 | const encodedValue = encode(options.value); |
| 111 | |
| 112 | // Clean & sanitize options |
| 113 | const expires = options.expires ? `; expires=${options.expires.replace('expires=', '')}` : ''; |
| 114 | |
| 115 | const path = (options.path || '/').replace('path=', ''); // Default is "path=/" |
| 116 | const domain = options.url != null && options.url.length > 0 ? `domain=${options.url}` : ''; |
| 117 | |
| 118 | document.cookie = `${encodedKey}=${encodedValue || ''}${expires}; path=${path}; ${domain};`; |
| 119 | } catch (error) { |
| 120 | return Promise.reject(error); |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | async deleteCookie(options: DeleteCookieOptions): Promise<void> { |
| 125 | try { |
| 126 | document.cookie = `${options.key}=; Max-Age=0`; |
| 127 | } catch (error) { |
| 128 | return Promise.reject(error); |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | async clearCookies(): Promise<void> { |
| 133 | try { |
| 134 | const cookies = document.cookie.split(';') || []; |
| 135 | for (const cookie of cookies) { |
| 136 | document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date().toUTCString()};path=/`); |
| 137 | } |
| 138 | } catch (error) { |
| 139 | return Promise.reject(error); |
| 140 | } |
| 141 | } |
| 142 | |
| 143 | async clearAllCookies(): Promise<void> { |
| 144 | try { |
| 145 | await this.clearCookies(); |
| 146 | } catch (error) { |
| 147 | return Promise.reject(error); |
| 148 | } |
nothing calls this directly
no outgoing calls
no test coverage detected