Skip to content
This repository has been archived by the owner on Nov 29, 2023. It is now read-only.

Commit

Permalink
changed: let cookie reading fail silently in context where document.c…
Browse files Browse the repository at this point in the history
…ookie is not accessible and throws an exception,

enketo/enketo-validate#77
  • Loading branch information
MartijnR committed Jul 29, 2020
1 parent f889e13 commit 098cb4e
Showing 1 changed file with 24 additions and 13 deletions.
37 changes: 24 additions & 13 deletions src/js/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -127,22 +127,33 @@ function readCookie( name ) {
return cookies[ name ];
}

const parts = document.cookie.split( '; ' );
cookies = {};

for ( let i = parts.length - 1; i >= 0; i-- ) {
const ck = parts[ i ].split( '=' );
// decode URI
ck[ 1 ] = decodeURIComponent( ck[ 1 ] );
// if cookie is signed (using expressjs/cookie-parser/), extract value
if ( ck[ 1 ].substr( 0, 2 ) === 's:' ) {
ck[ 1 ] = ck[ 1 ].slice( 2 );
ck[ 1 ] = ck[ 1 ].slice( 0, ck[ 1 ].lastIndexOf( '.' ) );
// In enketo-validate and perhaps other contexts, enketo-core is used in an empty page in a headless browser
// In such a context document.cookie throws an 'Access is denied for this document' error.
try {
const parts = document.cookie.split( '; ' );
cookies = {};

for ( let i = parts.length - 1; i >= 0; i-- ) {
const ck = parts[ i ].split( '=' );
// decode URI
ck[ 1 ] = decodeURIComponent( ck[ 1 ] );
// if cookie is signed (using expressjs/cookie-parser/), extract value
if ( ck[ 1 ].substr( 0, 2 ) === 's:' ) {
ck[ 1 ] = ck[ 1 ].slice( 2 );
ck[ 1 ] = ck[ 1 ].slice( 0, ck[ 1 ].lastIndexOf( '.' ) );
}
cookies[ ck[ 0 ] ] = decodeURIComponent( ck[ 1 ] );
}
cookies[ ck[ 0 ] ] = decodeURIComponent( ck[ 1 ] );

return cookies[ name ];

} catch( e ){
console.error( 'Cookie error', e );

return null;
}

return cookies[ name ];

}

/**
Expand Down

0 comments on commit 098cb4e

Please sign in to comment.