Palmabit-IT / react-cookie-law

React Cookie Law is a cookie-info banner compliance with the GDPR and the EU cookie law. It allows the user to give consent in a granular way.
115 stars 55 forks source link

callback events are called on every page load #31

Open carlosmgahete opened 3 years ago

carlosmgahete commented 3 years ago

Callback events are called not only when acepting cookies, but also on every page load.

I set the following alert messages for the cookie banner just for testing. And every time I move to a different page on my website the alert messages are shown.

     <CookieBanner
            message={config.cookieMessage}
            wholeDomain={true}
            onAccept={() => {
                alert("accept")
            }}
            onAcceptPreferences={() => {
                alert(`accept preferences`);
            }}
            onAcceptStatistics={() => { 
                alert(`accept stat`)
            }}
            onAcceptMarketing={() => { 
                alert(`accept market`)
            }}
            onDeclineStatistics={() => {
                alert(`decline stats`);
            }}
        />
benhubert commented 3 years ago

I can confirm that. Is this intended?

I'd like to enable tracking and send the first event after the user accepted the cookies, but with this, I send this event with every route change.

carlosmgahete commented 3 years ago

Just created a PR. If it is intended it is possible to use the following workaround.

However this still causes the onAcceptStatistics, onAcceptPreferences and onAcceptMarkleting, to be called twice when accepting the cookie banner.

const MyCookieBanner = () => (
     getCookie('rcl_consent_given') ?
         null :
        <CookieBanner
            message="my cookie message"
            wholeDomain={true}
            onAccept={() => {
                alert("accept")
            }}
            onAcceptStatistics={() => {
                alert("acceptStats")
            }}
            onDeclinePreferences={() => {
                alert("declinePrefs")
            }}
        />
)

function getCookie(key) {
    if (typeof document !== `undefined`) {
        var b = document.cookie.match("(^|;)\\s*" + key + "\\s*=\\s*([^;]+)");
    }
    return b ? b.pop() : "";
}

export default MyCookieBanner

Hope it helps!