-1

I have created a cookie banner related plugin for my site and now I would like to run the tracking code scripts once the user accepts the cookie banner.

I was able to inject the code with insertAdjacentHTML and now I would like to figure out how to execute this code so that the related tracking cookies are triggered.

I have seen eval(), but I have also seen that it is not a recommended function and it opens a security hole.

This is my code:

http.onreadystatechange = function() { //Call a function when the state changes.
  if(http.readyState == 4 && http.status == 200) {
    var con_cod = JSON.parse(this.responseText);
    var consents = con_cod["consents"];
    var head = document.getElementsByTagName("head")[0];
    var code_before_end_head = con_cod["code_before_end_head"];
    head.lastElementChild.insertAdjacentHTML("afterend", code_before_end_head);
    var now = new Date();
    var time = now.getTime();
    var expireTime = time + 24 * 60 * 60 * 1000;
    now.setTime(expireTime);
    document.cookie = cookie_name+'='+JSON.stringify(consents)+'; expires='+now.toUTCString()+'; SameSite=None; Secure; path=/';
  }
}
http.send(params);

How can I solve this situation? Of course I could also make the page reload, but this is not a good user experience for my visitors.

UPDATE:

I am using the code given here as recommended in the comments: Jquery cookie monitor

I am now able to see when the cookie is created and modified and give a response accordingly.

I am currently using alerts to make sure of this, but now I would need to run external JavaScript code such as Hotjar or Google Analytics code that if it is just injected (which I am doing) will not run.

This for example is the Hotjar JavaScript code that I am trying to run unsuccessfully:

<!-- Hotjar Tracking Code -->
<script id="gcbi-statistics">
    (function(h,o,t,j,a,r){
        h.hj=h.hj||function(){(h.hj.q=h.hj.q||[]).push(arguments)};
        h._hjSettings={hjid:7349271,hjsv:6};
        a=o.getElementsByTagName('head')[0];
        r=o.createElement('script');r.async=1;
        r.src=t+h._hjSettings.hjid+j+h._hjSettings.hjsv;
        a.appendChild(r);
    })(window,document,'https://static.hotjar.com/c/hotjar-','.js?sv=');
</script>
Matteo Feduzi
  • 55
  • 1
  • 8
  • You can add a call to your javascript function inside the if statement (where you check that the http.status==200) – Moudi Dec 14 '22 at 09:58
  • Can you leave a response with the code example? I added my code in the question, thanks! – Matteo Feduzi Dec 14 '22 at 10:01
  • 1
    If you're able to use jquery you could use this [example of a cookie listener](https://stackoverflow.com/questions/5908504/jquery-cookie-monitor) and then once your cookie is set, fire off the code you want. That way you won't need to eval. – IsThisJavascript Dec 14 '22 at 10:02
  • So I should simply add for example the Google Analytics code inside the function: listenCookieChange(cookie_name, function() { – Matteo Feduzi Dec 14 '22 at 10:06
  • If the tracking software that you are on about is the google analytics then yes, you would put it inside the anonymous function from that example code. – IsThisJavascript Dec 14 '22 at 10:08
  • The code works only in case the cookie changes its value, but how do I make it work even when the cookie is simply created? Also, I still haven't figured out how I execute the code by inserting it inside that function. – Matteo Feduzi Dec 17 '22 at 07:37

1 Answers1

0

I was able to find a much simpler solution.

This is the code I used to inject the various scripts and have them run once inserted:

// Remove comments and HTML tags using the replace function and a regular expression
var plainText = code_before_end_head[key_cod].replace(/<!--[\s\S]*?-->|<[^>]*>/g, '');

// Create a new script element
const script = document.createElement('script');

// Assigns an ID to the script element
script.id = 'gcbi-'+key_con;

// Assigns the code to be executed to the script element
script.innerHTML = plainText;

// Injects the script element into the head section of the document
document.head.appendChild(script);

There was no need to use the listenCookieChange function since everything is done via AJAX.

The code shown above was just inserted inside the request when receiving response from the PHP file.

I hope it can help!

Matteo Feduzi
  • 55
  • 1
  • 8