• Anonymous User 14018805

    (@anonymized-14018805)


    Is possible to make the script async in a way that when the user accept the cookie the scripts are added to the browser without the need to reload the page? (like cookiebot does)

    thank you

Viewing 9 replies - 1 through 9 (of 9 total)
  • Hi, this might be helpful, I’ve just finished coding it for my website after a bit of struggle.
    It uses wordpress standard ajax and seems to work, though I need to test it better.
    Please take it as it is, just a hint.

    in functions.php :

    /* ENQUEUE AND LOCALIZE */

    function child_theme_enqueue_scripts() {

    wp_enqueue_script(‘my_modules’, get_stylesheet_directory_uri().’/assets/js/’, array(‘jquery’), false, true);

    /* AJAX LOCALIZE */
    $args = array(
    ‘nonce’ => wp_create_nonce( ‘get-ajax-cookies-nonce’ ),
    ‘url’ => admin_url( ‘admin-ajax.php’ )
    );
    wp_localize_script( ‘my_modules’, ‘ajaxcookies’, $args );

    }
    add_action( ‘wp_enqueue_scripts’, ‘child_theme_enqueue_scripts’ );

    /* AJAX CALL OUTPUT */

    function get_ajax_cookies_release_scripts(){

    check_ajax_referer( ‘get-ajax-cookies-nonce’, ‘nonce’ );
    ob_start();
    ?>
    <!– Global site tag (gtag.js) – Google Analytics –>
    <script src=”https://www.googletagmanager.com/gtag/js?id=UA-XXXXXXXXX”></script&gt;
    <script>
    console.log(‘COOKIE SCRIPTS RELEASED’);
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag(‘js’, new Date());

    gtag(‘config’, ‘UA-XXXXXXXXX’);
    </script>
    <?php
    $data = ob_get_clean();
    wp_send_json_success( $data );

    }
    add_action( ‘wp_ajax_get_ajax_cookies_release_scripts’, ‘get_ajax_cookies_release_scripts’ );
    add_action( ‘wp_ajax_nopriv_get_ajax_cookies_release_scripts’, ‘get_ajax_cookies_release_scripts’ );

    In your modules.js (inside ready function):

    if($(‘#cookie-notice’).length){

    $(‘#cn-accept-cookie’).click(function(){

    var data = {
    action: ‘get_ajax_cookies_release_scripts’,
    nonce: ajaxcookies.nonce
    };
    $.post(ajaxcookies.url, data, function(res) {
    if( res.success && res.data != ”) {
    console.log(‘ajaxcookies success’);
    $(‘body’).append( res.data );
    } else {
    console.log(‘ajaxcookies no success’);
    console.log(res);
    }
    }).fail(function(xhr, textStatus, e) {
    console.log(‘ajaxcookies call fail’);
    console.log(xhr.responseText);
    });

    });

    });

    I hope it helps, you don’t need to modify the plugin code.
    Improvements are welcome!

    Thread Starter Anonymous User 14018805

    (@anonymized-14018805)

    Hi Daniel,

    sorry I don’t know very well PHP, can you explain me a bit the code and how can I adapt this for several 3rd part scripts?

    thanks

    That’s the question. It’d be the real solution to be able to link scripts loading (such ad Google Analytics or Facebook Pixel) to the click event on the Accept button. But without reloading the page.
    @danielez15 I’ll check your suggestion, even if I’m not very gook in Ajax stuff.
    I do hope that solution will be implemented in the plugin itself, it would be great.
    Thanks.

    It’ a standard wordpress/ajax workflow to load content without page reload, but you need to kwon what theme functions.php is and how ajax works in both php and javascript

    1. First you need to enqueue in your theme the javascript where you detect click event on button.
    2. then you localize that script so you can exchange data and vars between php and javascript in wordpress context.
    3. you create ajax handlers to respond with html (blocked stuff) when ajax call is placed.
    4. you bind click event to call an ajax request and print out the response from handlers.

    This is one of the first tutorial I found sometime ago:

    https://premium.wpmudev.org/blog/load-posts-ajax/?utm_expid=3606929-97.J2zL7V7mQbSNQDPrXwvBgQ.0&utm_referrer=https%3A%2F%2Fwww.google.it%2F

    christian70 I agree with you. Also a “change cookies preference” that resets the user choice would be appreciated. Something like this:

    $(‘#reset-cookies’).click(function(e){
    e.preventDefault();
    document.cookie = ‘cookie_notice_accepted=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;’;
    window.location.reload();
    });

    This is a quick fix that worked for me, but it reloads the page.
    It coul be mae in ajax as wll.

    The main problem with bloking scripts, or cookies, is that some contents load them later than page load, like embedded video, iframe, ect. so there’s no one solution for all.

    Thread Starter Anonymous User 14018805

    (@anonymized-14018805)

    Hi Daniel,

    really thanks for your answer. I will try it!

    In the meanwhile should be good to know if the plugin author thinked about implementing this functionality.

    Actually the unique plugin able to do it is cookiebot but it is really expensive

    • This reply was modified 6 years, 10 months ago by Anonymous User 14018805.

    Another step, in ajax handler you might replace hard-coded javascript with the one you put in cookie-notice admin option, so it becomes:

    function get_ajax_cookies_release_scripts(){
    check_ajax_referer( ‘get-ajax-cookies-nonce’, ‘nonce’ );
    ob_start();
    print_blocked_scripts(); /* this is new*/
    $data = ob_get_clean();
    wp_send_json_success( $data );
    }
    add_action( ‘wp_ajax_get_ajax_cookies_release_scripts’, ‘get_ajax_cookies_release_scripts’ );
    add_action( ‘wp_ajax_nopriv_get_ajax_cookies_release_scripts’, ‘get_ajax_cookies_release_scripts’ );

    /* this is new*/

    function print_blocked_scripts(){

    $options = get_option( ‘cookie_notice_options’, false );

    $allowed_html = apply_filters( ‘cn_refuse_code_allowed_html’, array_merge( wp_kses_allowed_html( ‘post’ ), array(
    ‘script’ => array(
    ‘type’ => array(),
    ‘src’ => array(),
    ‘charset’ => array(),
    ‘async’ => array()
    ),
    ‘noscript’ => array()
    )));

    echo apply_filters( ‘cn_refuse_code_scripts_html’, html_entity_decode( trim( wp_kses( $options[‘refuse_code’], $allowed_html ) ) ) );
    }

    @danielez15 I used your first version of the scripts and it seems it works well, or at least partially. I mean: I expect to get three cookies from GA: _ga, _gat and _gid. It’s weird because sometimes I get them all, sometimes only two of them (_gat is missing).
    I’ve got a very stupid question: how the ajax script works? I mean, I can see the cookies but I don’t get:

    <script>
    (function(i,s,o,g,r,a,m){i[‘GoogleAnalyticsObject’]=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,’script’,’https://www.google-analytics.com/analytics.js&#8217;,’ga’);
    ga(‘create’, ‘UA-XXXXXXXXX’, ‘auto’);
    ga(‘set’, ‘anonymizeIp’, true);
    ga(‘send’, ‘pageview’);
    </script>

    code in body.

    Thread Starter Anonymous User 14018805

    (@anonymized-14018805)

    Hi Danielez15,

    I tested your code in my website (https://www.gostudycanada.it/) but it does not work.

    I always need page reload to have the cookie in my browser.

    Do you know which could be the problem? I need any library to run the code?

    /* Cookie Notice Async */
    function get_ajax_cookies_release_scripts(){
    check_ajax_referer( ‘get-ajax-cookies-nonce’, ‘nonce’ );
    ob_start();
    print_blocked_scripts();
    $data = ob_get_clean();
    wp_send_json_success( $data );
    }
    add_action( ‘wp_ajax_get_ajax_cookies_release_scripts’, ‘get_ajax_cookies_release_scripts’ );
    add_action( ‘wp_ajax_nopriv_get_ajax_cookies_release_scripts’, ‘get_ajax_cookies_release_scripts’ );

    function print_blocked_scripts(){

    $options = get_option( ‘cookie_notice_options’, false );

    $allowed_html = apply_filters( ‘cn_refuse_code_allowed_html’, array_merge( wp_kses_allowed_html( ‘post’ ), array(
    ‘script’ => array(
    ‘type’ => array(),
    ‘src’ => array(),
    ‘charset’ => array(),
    ‘async’ => array()
    ),
    ‘noscript’ => array()
    )));

    echo apply_filters( ‘cn_refuse_code_scripts_html’, html_entity_decode( trim( wp_kses( $options[‘refuse_code’], $allowed_html ) ) ) );
    }

    @blackster000, when you disable “reload page” in options, them you accept cookies on frontend, the plugin set the cookie_notice_accepted cookie to true by itself.
    On your wesite it doesn’t happen, something’s going wrong: check your log console error.

    @christian70, if it save cookies, it means somewhere the held code is printed, so you should see this line before the end of body closing tag:

    <!– Global site tag (gtag.js) – Google Analytics –>

    By the way, I think sometimes cache messes things up a little bit.

Viewing 9 replies - 1 through 9 (of 9 total)
  • The topic ‘Async script’ is closed to new replies.