Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CookiesEu gem to add cookie consent doesn't disappear after pressing ok

So I've added CookiesEu gem to my application to add cookie consent. But the problem is the text: Cookies help us deliver our services. By using our services, you agree to our use of cookies. OK Learn more stays in sight after pressing the OK button. Whereas I want it to disappear after pressing OK.

in the documentation it says: This gem uses a cookie called cookie_eu_consented to track whether a user has accepted the cookie notice and whether it needs to be shown again or not. But the cookie notice is shown even after accepting the cookie.

p.s. I put the = render 'cookies_eu/consent_banner', link: '/cookies' in the footer

like image 997
ga4696 Avatar asked Nov 24 '25 19:11

ga4696


2 Answers

If you are using Rails 6 or above JavaScript is now delivered using webpacker. This breaks the current file structure and causes the JavaScript that would normally deal with the 'Ok' button to fail.

You can find a solution below:

To make this work with Webpacker. Your JavaScript code must be imported as a webpack dependency instead of embedding JS in tags in the view.

Step one:

Make sure the following tags are in your layout:

   <%= stylesheet_pack_tag 'application' %>
   <%= javascript_pack_tag 'application' %>

Second:

Just as in the README The banner HTML should be in your layout/view, i.e., <div id="cookies-eu-banner" style="display: none;">...</div>

Third:

Add a JS file for initializing the banner somewhere in app/javascript/, (but not in app/javascript/packs), like app/javascript/src/add-banner.js. Here, you'll import the library (and CSS if you want) and initialize it when the DOM content has loaded:

// app/javascript/src/add-eu-banner.js

import CookiesEuBanner from 'cookies-eu-banner'
import 'cookies-eu-banner/css/cookies-eu-banner.default.css'

document.addEventListener('DOMContentLoaded', () => {
  new CookiesEuBanner(() => {
    console.log('Cookies EU Banner accepted');
  })
})

Finally:

Add that file as a webpack dependency by adding an import statement in the "application.js" pack file:

// app/javascript/packs/application.js

import '../src/add-eu-banner'

If you are using a version of Rails lower than 6 I suggest posting your code up so people can take a deeper look into your issue.

like image 155
Gino Avatar answered Nov 27 '25 11:11

Gino


Make sure that

//= require cookies_eu

was added to your application.js after you ran bundle exec rails g cookies_eu:install

like image 40
Sal Avatar answered Nov 27 '25 12:11

Sal