Skip to content

Commit

Permalink
Merge pull request #1161 from cdrini/fix/iframe-sandbox
Browse files Browse the repository at this point in the history
Don't error if cookies are blocked
  • Loading branch information
cdrini authored Mar 21, 2023
2 parents a6dc863 + f4b7fca commit 62661df
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
23 changes: 21 additions & 2 deletions src/util/docCookies.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,22 @@
* http://www.gnu.org/licenses/gpl-3.0-standalone.html
*/

/**
* Check to see if the browser has cookies enabled.
* Accessing document.cookies errors if eg iframe with sandbox enabled.
* @returns {boolean}
*/
export function areCookiesBlocked(doc = document) {
try {
doc.cookie;
return false;
} catch (e) {
return true;
}
}

const COOKIES_BLOCKED = areCookiesBlocked();

/**
* Get specific key's value stored in cookie
*
Expand All @@ -17,7 +33,7 @@
* @returns {string|null}
*/
export function getItem(sKey) {
if (!sKey) return null;
if (COOKIES_BLOCKED || !sKey) return null;

return decodeURIComponent(
// eslint-disable-next-line no-useless-escape
Expand All @@ -34,9 +50,11 @@ export function getItem(sKey) {
* @param {string} [sDomain] domain name
* @param {boolean} [bSecure]
*
* @returns {true}
* @returns {boolean}
*/
export function setItem(sKey, sValue, vEnd, sPath, sDomain, bSecure) {
if (COOKIES_BLOCKED) return false;

document.cookie = encodeURIComponent(sKey) + '=' + encodeURIComponent(sValue)
+ (vEnd ? `; expires=${vEnd.toUTCString()}` : '')
+ (sDomain ? `; domain=${sDomain}` : '')
Expand All @@ -56,6 +74,7 @@ export function setItem(sKey, sValue, vEnd, sPath, sDomain, bSecure) {
* @returns {boolean}
*/
export function removeItem(sKey, sPath, sDomain) {
if (COOKIES_BLOCKED) return false;
// eslint-disable-next-line
if (!hasItem(sKey)) return false;

Expand Down
9 changes: 9 additions & 0 deletions tests/jest/util/docCookies.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,12 @@ describe('Helper function: set and get cookie item', () => {
expect(docCookies.getItem('test-cookie')).toEqual('jack-sparow');
});
});

describe('isCookiesBlocked', () => {
test('return true if cookies are blocked', () => {
expect(docCookies.areCookiesBlocked({ get cookie() { throw new Error(); }})).toBeTruthy();
});
test('return false if cookies are not blocked', () => {
expect(docCookies.areCookiesBlocked({ cookie: 'blah' })).toBeFalsy();
});
});

0 comments on commit 62661df

Please sign in to comment.