创建Cookie横幅

时间:2019-04-21 12:48:04

标签: javascript php css html5

目标是使用HTML,JavaScript,CSS +和PHP创建一个简单的Cookie横幅。

我们已经创建了HTML和CSS,但仅在用户单击“接受”时,我们无法弄清楚如何设置Cookies(Facebook Pixel + Google Analytics)。

1 个答案:

答案 0 :(得分:0)

这是一个简单的示例,使用JavaScript为我自己使用的cookie横幅设置cookie(不想使用库)。

HTML:

<div class="cookie-banner js-cookie-banner">
    We use ...
    <button class="js-cookie-dismiss">Accept</button>
</div>

JavaScript(使用ES6,因此可能需要转译,否则浏览器支持应该可以):

// Key under which name the cookie is saved
const cookieName = 'cookieconsent';
// The value could be used to store different levels of consent
const cookieValue = 'dismissed';

function dismiss() {
    const date = new Date();
    // Cookie is valid 1 year: now + (days x hours x minutes x seconds x milliseconds)
    date.setTime(date.getTime() + (365 * 24 * 60 * 60 * 1000));
    // Set cookie
    document.cookie = `${cookieName}=${cookieValue};expires=${date.toUTCString()};path=/`;

    // You probably want to remove the banner
    document.querySelector('.js-cookie-banner').remove();
}

// Get button element
const buttonElement = document.querySelector('.js-cookie-dismiss');
// Maybe cookie consent is not present
if (buttonElement) {
    // Listen on button click
    buttonElement.addEventListener('click', dismiss);
}

仅当未设置Cookie时,PHP应用程序才应包含cookie同意横幅的标记。因此,请使用以下内容:

if (!(array_key_exists('cookieconsent', $_COOKIE) && $_COOKIE['cookieconsent'] === 'dismissed')) {
    // Output the HTML
}

您也可以仅在这种情况下包括JavaScript。另外,您可以检查Cookie是否在JavaScript中设置:

function isDismissed() {
    // Get all cookies as string
    const decodedCookie = decodeURIComponent(document.cookie);
    // Separate cookies
    const cookies = decodedCookie.split(';');
    for (let cookie of cookies) {
        cookie = cookie.trim();
        // Check if cookie is present
        if (cookie === `${cookieName}=${cookieValue}`) {
            return true;
        }
    }

    return false;
}

在CodePen上进行检查,StackOverflow不支持Cookies:https://codepen.io/KiwiKilian/pen/PgaVMb

您可以查看是否在开发人员工具中设置了Cookie,例如在Chrome dev tools under application中,然后再次将其删除。