cookie.js (1609B)
1 /* This Source Code Form is subject to the terms of the Mozilla Public 2 * License, v. 2.0. If a copy of the MPL was not distributed with this 3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 4 5 /* global browser, ConditionBase */ 6 7 /** 8 * COOKIE condition 9 */ 10 class ConditionCookie extends ConditionBase { 11 static STORAGE_KEY = "cookies-"; 12 13 constructor(factory, desc) { 14 super(factory, desc); 15 } 16 17 async init() { 18 const { domain } = this.desc; 19 if (!domain) { 20 return; 21 } 22 23 let cache = this.factory.retrieveData(ConditionCookie.STORAGE_KEY + domain); 24 if (Array.isArray(cache)) { 25 return; 26 } 27 28 try { 29 const cookies = await browser.cookies.getAll({ domain }); 30 cache = Array.isArray(cookies) ? cookies : []; 31 } catch (e) { 32 cache = []; 33 } 34 35 this.factory.storeData(ConditionCookie.STORAGE_KEY + domain, cache); 36 } 37 38 check() { 39 if (!this.desc.domain || !this.desc.name) { 40 return false; 41 } 42 43 const cookies = 44 this.factory.retrieveData( 45 ConditionCookie.STORAGE_KEY + this.desc.domain 46 ) || []; 47 const cookie = cookies.find(c => c && c.name === this.desc.name); 48 if (!cookie) { 49 return false; 50 } 51 52 if ( 53 typeof this.desc.value === "string" && 54 cookie.value !== this.desc.value 55 ) { 56 return false; 57 } 58 59 if ( 60 typeof this.desc.value_contain === "string" && 61 (typeof cookie.value !== "string" || 62 !cookie.value.includes(this.desc.value_contain)) 63 ) { 64 return false; 65 } 66 67 return true; 68 } 69 } 70 71 globalThis.ConditionCookie = ConditionCookie;