If you are creating cookies for a site, you need to warn the user about it. In the example below, we will first read the cookie. If the cookie is not found, we will create one and then notify the user about it. You can implement the warning mechanism in the App component of your project.
Add Dependency
Add snack-bar dependency to the App component:
Create a Method
Create a User Interface Method in the App component. Check the box "Call on load" to make it run automatically when the user launches the app.
Paste the following code in this method:
let key = 'acceptCookies';
debug('acceptCookies cookie', readCookie(key));
if (!readCookie(key)) {
setTimeout(() => {
this.snackBar.open(
'We use cookies on this site to improve performance, for analytics and for advertising. By browsing this site you are agreeing to this. For more information please read our Privacy policy.',
'Close'
);
}, 1000);
createCookie(key, 'yes');
}
function createCookie(name, value) {
document.cookie = name + '=' + value + '; path=/';
}
function readCookie(name) {
var nameEQ = name + '=';
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
In the above code, we first call the function readCookie() to check if the cookie with the name "acceptCookies" exist. If it does exist, it means that the user has already visited the page and that we don't need to show any cookie warning.
If the cookie is not found, it means that either the user is visiting the site for the first time from that device or the user has cleared the cookies. In that case, we open a snackbar to display a cookie warning and then we create the cookie by calling createCookie().