locked
How to use Cookie Consent with SweetAlert2 RRS feed

  • Question

  • User248267340 posted

    I'm in the process of learning Javascript, so it will be awhile before this sinks in. I have code for Cookie Consent, which is the default for MVC Core 3.1, and looks like this:

    @using Microsoft.AspNetCore.Http.Features
    
    @{
        var consentFeature = Context.Features.Get<ITrackingConsentFeature>();
        var showBanner = !consentFeature?.CanTrack ?? false;
        var cookieString = consentFeature?.CreateConsentCookie();
    }
    
    
    @if (showBanner)
    {
        <!-- <div style="; top: 0; z-index: 9; opacity: 0.8"> -->
        <div>
            <div id="cookieConsent" class="alert alert-info alert-dismissible fade show" role="alert">
                This website uses cookies to store data for your order. If you do not wish to use cookies, then this website will be
                unable to track your order, and will render the shopping cart useless. If you would still like to order but do not want
                cookies on your device, please contact us and we would be happy to help you!<br />
                <a class="alert-link" asp-area="" asp-controller="Home" asp-action="Privacy">Learn More</a>.
                <button type="button" class="accept-policy myclose" data-dismiss="alert" aria-label="Close" data-cookie-string="@cookieString">
                    <span aria-hidden="true">Accept</span>
                </button>
            </div>
        </div>
    
        <script>
            (function () {
                var button = document.querySelector("#cookieConsent button[data-cookie-string]");
                button.addEventListener("click", function (event) {
                    document.cookie = button.dataset.cookieString;
                }, false);
            })();
        </script>
    }
    

    I'd like to display the cookie consent banner using Sweetalert. I could do this:

    @if (showBanner)
        {
            <script>
                Swal.fire({
                    title: 'Cookie Consent',
                    text: 'This website uses Cookies, which are tiny files placed on your computer for ordering. If you would rather not use cookies, please contact us!',
                    width: '100%',
                    height: 100,
                    position: 'bottom',
                    showDenyButton: true,
                    confirmButtonText: 'Accept',
                    denyButtonText: 'Reject',
                }).then((result) => {
                    if (result.isConfirmed) {
                        //swal.fire('Saved', '', 'Success')
    
                (function () {
    
                        var button = document.querySelector("#cookieConsent button[data-cookie-string]");
                        button.addEventListener("click", function (event) {
                            document.cookie = button.dataset.cookieString;
                        }, false);
    
                })();
    
    
                    } else if (result.isDenied) {
                        swal.fire('Please contact seller for assistance', '', 'info')
                    }
                })
            </script>
        }

    But for some reason, it's not working right. If I start my project, the banner shows up, and if I login or register, it also runs. That tells

    the code to set the cookie status is not working correctly inside the SweetAlert.

    Is there something you can spot, that will help me get things to run correctly?

    Wednesday, October 7, 2020 11:12 PM

Answers

  • User-1330468790 posted

    Hi coreysan,

     

    Now your problem is that you can not make the sweetalert working, correct?

     

    If you have followed this tutorial, https://docs.microsoft.com/en-us/aspnet/core/security/gdpr?view=aspnetcore-3.1, you could successfully make the codes working following below steps:

     

    [Startup.cs] for registering CookiePolicyOptions service:

    The first thing you need to confirm that the consent content could appear normally (with button).

    In another words, could you please confirm whether your startup.cs file looks like below (especially in background color orange)?

    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
    
        public IConfiguration Configuration { get; }
    
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential 
                // cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                // requires using Microsoft.AspNetCore.Http;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });
    
            services.AddRazorPages();
        }
    
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }
    
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();
    
            app.UseRouting();
    
            app.UseAuthorization();
    
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
            });
        }
    }

    [_Layout.cshtml] for including JQuery:

    If everything runs well, you might need to confirm that you have included JQuery in layout since you mentioned it is a default MVC core project.

        <script src="~/lib/jquery/dist/jquery.min.js"></script>
        <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
        <script src="~/js/site.js" asp-append-version="true"></script>
        @RenderSection("Scripts", required: false)

    [RazorView] for adding sweetalert2.js

    The last step is to check if you have integrated the sweetalert correctly in the page.

    @using Microsoft.AspNetCore.Http.Features
    
    @{
        ViewData["Title"] = "Consent Cookies";
    }
    
    @{
        var consentFeature = Context.Features.Get<ITrackingConsentFeature>();
        var showBanner = !consentFeature?.CanTrack ?? false;
        var cookieString = consentFeature?.CreateConsentCookie();
    }
    
    
    
    
    <h3>Consent Cookies</h3>
    
    @if (showBanner)
    {
        <!-- <div style="; top: 0; z-index: 9; opacity: 0.8"> -->
        <div>
            <div id="cookieConsent" class="alert alert-info alert-dismissible fade show" role="alert">
                This website uses cookies to store data for your order. If you do not wish to use cookies, then this website will be
                unable to track your order, and will render the shopping cart useless. If you would still like to order but do not want
                cookies on your device, please contact us and we would be happy to help you!<br />
                <a class="alert-link" asp-area="" asp-controller="Home" asp-action="Privacy">Learn More</a>.
                <button type="button" class="accept-policy myclose" data-dismiss="alert" aria-label="Close" data-cookie-string="@cookieString">
                    <span aria-hidden="true">Accept</span>
                </button>
            </div>
        </div>
    
        <script>
            (function () {
                var button = document.querySelector("#cookieConsent button[data-cookie-string]");
                button.addEventListener("click", function (event) {
                    document.cookie = button.dataset.cookieString;
                }, false);
            })();
        </script>
    }
    
    @section scripts{
    
    
        <link href="//cdn.jsdelivr.net/npm/@@sweetalert2/theme-dark@4/dark.css" rel="stylesheet">
        <script src="//cdn.jsdelivr.net/npm/sweetalert2@10/dist/sweetalert2.min.js">
        </script>
    
        @if (showBanner)
        {
            <script>
                
                    Swal.fire({
                        title: 'Cookie Consent',
                        text: 'This website uses Cookies, which are tiny files placed on your computer for ordering. If you would rather not use cookies, please contact us!',
                        width: '100%',
                        height: 100,
                        position: 'bottom',
                        showDenyButton: true,
                        confirmButtonText: 'Accept',
                        denyButtonText: 'Reject',
                    }).then((result) => {
                        if (result.isConfirmed) {
                            swal.fire('Saved', '', 'Success')
                          // then the alert would not popup again and again
                            document.cookie = '@cookieString';
    
    
                        } else if (result.isDenied) {
                            swal.fire('Please contact seller for assistance', '', 'info')
                        }
                    })
                
    
            </script>
        }
    }

    Demo:

     

    If you still have problem, you could post your codes so that we are able to target the problem easier.

     

    Best regards,

    Sean

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, October 9, 2020 7:57 AM

All replies

  • User-1330468790 posted

    Hi coreysan,

     

    I have tested your codes and reproduced the problem. It seems missing the jquery reference when Swal.fire() is working. The jquery reference in asp.net core project is always rendered in script section which is after the body section

     

    You could modify the page codes as below:

    @using Microsoft.AspNetCore.Http.Features
    
    @{
        ViewData["Title"] = "Consent Cookies";
    }
    
    @{
        var consentFeature = Context.Features.Get<ITrackingConsentFeature>();
        var showBanner = !consentFeature?.CanTrack ?? false;
        var cookieString = consentFeature?.CreateConsentCookie();
    }
    
    
    
    <h3>Consent Cookies</h3>
    
    @if (showBanner)
    {
        <!-- <div style="; top: 0; z-index: 9; opacity: 0.8"> -->
        <div>
            <div id="cookieConsent" class="alert alert-info alert-dismissible fade show" role="alert">
                This website uses cookies to store data for your order. If you do not wish to use cookies, then this website will be
                unable to track your order, and will render the shopping cart useless. If you would still like to order but do not want
                cookies on your device, please contact us and we would be happy to help you!<br />
                <a class="alert-link" asp-area="" asp-controller="Home" asp-action="Privacy">Learn More</a>.
                <button type="button" class="accept-policy myclose" data-dismiss="alert" aria-label="Close" data-cookie-string="@cookieString">
                    <span aria-hidden="true">Accept</span>
                </button>
            </div>
        </div>
    
        <script>
            (function () {
                var button = document.querySelector("#cookieConsent button[data-cookie-string]");
                button.addEventListener("click", function (event) {
                    document.cookie = button.dataset.cookieString;
                }, false);
            })();
        </script>
    }
    
    @section scripts{
    
    
        <link href="//cdn.jsdelivr.net/npm/@@sweetalert2/theme-dark@4/dark.css" rel="stylesheet">
        <script src="//cdn.jsdelivr.net/npm/sweetalert2@10/dist/sweetalert2.min.js">
        </script>
    
        @if (showBanner)
        {
            <script>
                
                    Swal.fire({
                        title: 'Cookie Consent',
                        text: 'This website uses Cookies, which are tiny files placed on your computer for ordering. If you would rather not use cookies, please contact us!',
                        width: '100%',
                        height: 100,
                        position: 'bottom',
                        showDenyButton: true,
                        confirmButtonText: 'Accept',
                        denyButtonText: 'Reject',
                    }).then((result) => {
                        if (result.isConfirmed) {
                            //swal.fire('Saved', '', 'Success')
    
                            (function () {
    
                                var button = document.querySelector("#cookieConsent button[data-cookie-string]");
                                button.addEventListener("click", function (event) {
                                    document.cookie = button.dataset.cookieString;
                                }, false);
    
                            })();
    
    
                        } else if (result.isDenied) {
                            swal.fire('Please contact seller for assistance', '', 'info')
                        }
                    })
                
    
            </script>
        }
    }
    

    Demo:

     

    Hope helps.

    Best regards,

    Sean

    Thursday, October 8, 2020 3:17 AM
  • User248267340 posted

    Hello Sean,

    I really appreciate your help. I'm learning a lot as I go!

    The default MVC Core 3.1 code works just fine, I just don't care for the way it looks. So I thought if I actually replaced most of the Core 3.1 code with Sweetalert2, it would look better.

    When I tried your suggestion, it prevented the sweetalert banner from appearing at all.

    I'm sure the way my project is laid out has something to do with it. So maybe I should ask my question differently:

    Is there a way to use just SweetAlert to display Cookie Consent banner, and if confirmed, do whatever I'm supposed to do to get the cookiestring set so it won't ask again and again.

    Apparently the Core 3.1 code sets the cookiestring properly because it's using <div id=#CookieConsent> and a button to drive the setting of the document.cookie. I don't have any idea how this all works anyway!

    So is there a way to get SweetAlert to fire, and then use Javascript to set the cookiestring without the Core 3.1 code?

    Thursday, October 8, 2020 7:50 PM
  • User-1330468790 posted

    Hi coreysan,

     

    Now your problem is that you can not make the sweetalert working, correct?

     

    If you have followed this tutorial, https://docs.microsoft.com/en-us/aspnet/core/security/gdpr?view=aspnetcore-3.1, you could successfully make the codes working following below steps:

     

    [Startup.cs] for registering CookiePolicyOptions service:

    The first thing you need to confirm that the consent content could appear normally (with button).

    In another words, could you please confirm whether your startup.cs file looks like below (especially in background color orange)?

    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
    
        public IConfiguration Configuration { get; }
    
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential 
                // cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                // requires using Microsoft.AspNetCore.Http;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });
    
            services.AddRazorPages();
        }
    
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }
    
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();
    
            app.UseRouting();
    
            app.UseAuthorization();
    
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
            });
        }
    }

    [_Layout.cshtml] for including JQuery:

    If everything runs well, you might need to confirm that you have included JQuery in layout since you mentioned it is a default MVC core project.

        <script src="~/lib/jquery/dist/jquery.min.js"></script>
        <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
        <script src="~/js/site.js" asp-append-version="true"></script>
        @RenderSection("Scripts", required: false)

    [RazorView] for adding sweetalert2.js

    The last step is to check if you have integrated the sweetalert correctly in the page.

    @using Microsoft.AspNetCore.Http.Features
    
    @{
        ViewData["Title"] = "Consent Cookies";
    }
    
    @{
        var consentFeature = Context.Features.Get<ITrackingConsentFeature>();
        var showBanner = !consentFeature?.CanTrack ?? false;
        var cookieString = consentFeature?.CreateConsentCookie();
    }
    
    
    
    
    <h3>Consent Cookies</h3>
    
    @if (showBanner)
    {
        <!-- <div style="; top: 0; z-index: 9; opacity: 0.8"> -->
        <div>
            <div id="cookieConsent" class="alert alert-info alert-dismissible fade show" role="alert">
                This website uses cookies to store data for your order. If you do not wish to use cookies, then this website will be
                unable to track your order, and will render the shopping cart useless. If you would still like to order but do not want
                cookies on your device, please contact us and we would be happy to help you!<br />
                <a class="alert-link" asp-area="" asp-controller="Home" asp-action="Privacy">Learn More</a>.
                <button type="button" class="accept-policy myclose" data-dismiss="alert" aria-label="Close" data-cookie-string="@cookieString">
                    <span aria-hidden="true">Accept</span>
                </button>
            </div>
        </div>
    
        <script>
            (function () {
                var button = document.querySelector("#cookieConsent button[data-cookie-string]");
                button.addEventListener("click", function (event) {
                    document.cookie = button.dataset.cookieString;
                }, false);
            })();
        </script>
    }
    
    @section scripts{
    
    
        <link href="//cdn.jsdelivr.net/npm/@@sweetalert2/theme-dark@4/dark.css" rel="stylesheet">
        <script src="//cdn.jsdelivr.net/npm/sweetalert2@10/dist/sweetalert2.min.js">
        </script>
    
        @if (showBanner)
        {
            <script>
                
                    Swal.fire({
                        title: 'Cookie Consent',
                        text: 'This website uses Cookies, which are tiny files placed on your computer for ordering. If you would rather not use cookies, please contact us!',
                        width: '100%',
                        height: 100,
                        position: 'bottom',
                        showDenyButton: true,
                        confirmButtonText: 'Accept',
                        denyButtonText: 'Reject',
                    }).then((result) => {
                        if (result.isConfirmed) {
                            swal.fire('Saved', '', 'Success')
                          // then the alert would not popup again and again
                            document.cookie = '@cookieString';
    
    
                        } else if (result.isDenied) {
                            swal.fire('Please contact seller for assistance', '', 'info')
                        }
                    })
                
    
            </script>
        }
    }

    Demo:

     

    If you still have problem, you could post your codes so that we are able to target the problem easier.

     

    Best regards,

    Sean

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, October 9, 2020 7:57 AM
  • User248267340 posted

    Sean,

    Once again - thank you so much for helping me with this.

    I confirmed that 1) the startup.cs is correct, 2) layout loads the jquery, and 3) the file with all the cookie consent code is as you stated.

    Before we go any further, I would like to ask one thing:

    I work at a job with high security, so I'm not allowed to access the Internet on this desktop. All files must be local.

    So usually when I include an app like SweetAlert, I download the contents of all the css and js files, and include them locally.

    I can get SweetAlert to fire using the normal means of setup, like this:

    1. I download the needed css and js file contents
    2. I point to the files locally from the _Layout file.
    3. Then I call swal.fire where ever I want.

    Since I'm locked out of the Internet, I can't load the following lines:

        <link href="//cdn.jsdelivr.net/npm/@@sweetalert2/theme-dark@4/dark.css" rel="stylesheet">
        <script src="//cdn.jsdelivr.net/npm/sweetalert2@10/dist/sweetalert2.min.js"></script>

    Usually I would download the files, but I've never seen links like this where there are embedded "@" symbols. Is there a way to download the contents from the 2 links above?

    In the meantime, I will test all this over the weekend at my home (where I do have full Internet access), and see how it all goes!

    Friday, October 9, 2020 4:56 PM
  • User248267340 posted

    Sean,

    I finally fixed it. I had to surround the variable @cookieString with single quotes inside the Sweetalert2 block, as you did. That fixed everything!

    Thanks so much Sean!

    Saturday, October 10, 2020 12:46 AM