<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Riccardo Malesani on Medium]]></title>
        <description><![CDATA[Stories by Riccardo Malesani on Medium]]></description>
        <link>https://medium.com/@riccardo.malesani?source=rss-a543d4c33792------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*_GIMx1yt_mphGO48Ge02Mw.jpeg</url>
            <title>Stories by Riccardo Malesani on Medium</title>
            <link>https://medium.com/@riccardo.malesani?source=rss-a543d4c33792------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 11:36:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@riccardo.malesani/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Easy Universal Analytics backup with Node.js]]></title>
            <link>https://medium.com/@riccardo.malesani/easy-universal-analytics-backup-with-node-js-e88cc81e18c6?source=rss-a543d4c33792------2</link>
            <guid isPermaLink="false">https://medium.com/p/e88cc81e18c6</guid>
            <category><![CDATA[cloud-functions]]></category>
            <category><![CDATA[google-big-query]]></category>
            <category><![CDATA[universal-analytics]]></category>
            <category><![CDATA[google-analytics]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Riccardo Malesani]]></dc:creator>
            <pubDate>Sat, 15 Jun 2024 14:11:48 GMT</pubDate>
            <atom:updated>2024-06-15T14:11:48.816Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*oy0H0JPNUAlvmqWn_qBgfQ@2x.jpeg" /></figure><p>Just a couple of weeks ahead before <strong>Google Universal Analytics</strong> ultimately expires and neither the properties nor the data inside will be available any longer.</p><p>While there are several ways of backing up the data, most of them are not free connectors or they require additional installations in your localhost or cloud environment (in python, for example, often pandas and other packages are required).</p><p>I created a <strong>Node.js</strong> module script, based on the (UA) Legacy Reporting APIs, that can easily run on Google Cloud Functions or Cloud Run services, natively integrated with your BigQuery setup and fast to retrieve and store your old UA data. It basically does the following:</p><ul><li>It leverages a GCP Service Account (and its downloadable JSON key) you can quickly create via IAM. The same Service Account email must be given View privilege to the UA you want to extract data from.</li><li>It needs you to create the destination table in BigQuery, with DATE field, followed by Dimensions and Metrics fields. Those need to have the same names used by the API itself, so my script can automatically infer them.</li><li>It needs to be installed together with some environment variables (like DATASET, PRJ, TABLE or the PKEY — the private key you download from the Service Account details.</li><li>It quickly and fully asynchronously retrieve the data despite of the API limit of 10.000 rows per request, because it uses pagination until the full results are done.</li></ul><p>You can find the script, along with more README info, in my public git repo: <strong>https://github.com/rimalesani/ua_backup</strong></p><p>Drop some comments here or contact me in case of need.</p><p>Don’t worry, with this you’re on time for backing up your UA data before it’s too late.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e88cc81e18c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sharing Google Consent with iframes (part 2)]]></title>
            <link>https://medium.com/@riccardo.malesani/sharing-google-consent-with-iframes-part-2-d44d7f584a40?source=rss-a543d4c33792------2</link>
            <guid isPermaLink="false">https://medium.com/p/d44d7f584a40</guid>
            <category><![CDATA[google-analytics]]></category>
            <category><![CDATA[promises-in-javascript]]></category>
            <category><![CDATA[iframe-embed]]></category>
            <category><![CDATA[google-tag-manager]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Riccardo Malesani]]></dc:creator>
            <pubDate>Tue, 12 Mar 2024 21:29:46 GMT</pubDate>
            <atom:updated>2024-03-12T21:29:46.751Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Cf-C9WMwNL6BT2YdHWzEg.png" /></figure><p>This is the second part of the <a href="https://medium.com/@riccardo.malesani/sharing-google-consent-with-iframes-part-1-9e00600b68ff">article</a> on sharing Google Consent status with third-party iframes (<strong>if single-page apps with no storage needed</strong>). The previous article closed with listing all the critical Google Tag Manager building blocks, without digging further into them. This is what I’m going to do here below:</p><p><strong>1 — The {{Consent grabber}} custom variable</strong></p><p>The first element we need is used in the parent page to retrieve the most recent consent status and to transform it in the combined Google Consent codes. This is a HTML custom variable which final output looks like “111” if both analytics and ad storages are granted when the parent page, and therefore its iframe, is loaded. The variable is as follows:</p><pre>function() <br> function consentStatus(storage) {<br>	var El = window[&quot;dataLayer&quot;],<br>	    List = [];<br>    for (i in El) { <br>        if (JSON.stringify(El[i])) var Value = JSON.stringify(El[i]).replaceAll(/\&quot;\d{1,}\&quot;:/g, &quot;&quot;); <br>	    if (Value.match(/&quot;consent&quot;,&quot;(default|update)&quot;/)) { <br>	    	var Reg = new RegExp(storage + &#39;_storage&quot;:&quot;([^&quot;,]+)&#39;);<br>	    	if (Value.match(Reg)) List.push(Value.match(Reg)[1]);	    	 <br>	    }        <br>    } <br>    return List[List.length-1];<br> }<br> switch (true) {<br>  case consentStatus(&quot;analytics&quot;)==&quot;granted&quot; &amp;&amp; consentStatus(&quot;ad&quot;)==&quot;granted&quot;:<br>    return &quot;111&quot;;<br>    break;<br>  case consentStatus(&quot;analytics&quot;)==&quot;granted&quot; &amp;&amp; consentStatus(&quot;ad&quot;)==&quot;denied&quot;:<br>    return &quot;101&quot;;<br>    break;<br>  case consentStatus(&quot;analytics&quot;)==&quot;denied&quot; &amp;&amp; consentStatus(&quot;ad&quot;)==&quot;granted&quot;:<br>    return &quot;110&quot;;<br>    break; <br>  case consentStatus(&quot;analytics&quot;)==&quot;denied&quot; &amp;&amp; consentStatus(&quot;ad&quot;)==&quot;denied&quot;:<br>    return &quot;100&quot;;<br>    break;   <br>  default:<br>    return &quot;101&quot;;<br> }  <br>}</pre><p><em>* My example takes analytics and ad storages into consideration only. If you need others (e.g. if you use tags based on “personalization” or “functionality” storages, inside the iframe), you have to enrich or change this code.</em></p><p>The “consentStatus” function, on top, is <a href="https://medium.com/@riccardo.malesani/fetching-the-google-last-consents-1466867bd22f">my old creation</a> to fetch the most recent consent statuses from the page. This is used in the next “switch” construct to build the “111”, “101”…codes that <strong>will be dynamically appended to the iframe source URL</strong>. Note the default switch case is “101” because my website has analytics granted by design. If your case is the opposite, just set it to “100”. This variable is taken as advantage in the following element, the…</p><p><strong>2 — “Iframe handler” tag</strong></p><p>This tag has two purposes: take the GA ID from the parent page (the Consent status has to be passed to the iframe together with it and only when it is available) and to update the iframe’s URL with it and with the consent code returned by the previously described custom variable. This is also a custom HTML that looks like as follows:</p><pre>//get the GA ID: <br>function getGAId() {<br>  var ga = window[window[&#39;GoogleAnalyticsObject&#39;]];<br>  var tracker;<br>  if (ga &amp;&amp; typeof ga.getAll === &#39;function&#39;) {<br>    tracker = ga.getAll()[0];<br>    gastring = (new window.gaplugins.Linker(tracker)).decorate(&quot;?&quot;); <br>    gastringdef = gastring.substring(6,gastring.length);<br>  } else { gastringdef = &quot;&quot;; }<br>  return gastringdef;<br>}  <br>  <br>var timeout = 1000000; //How much we can wait for GA ID to be available<br>// This is the promise code:<br>function ensureGAIsSet(timeout) {<br>    var start = Date.now();<br>    return new Promise(waitForGA);<br>    <br>    function waitForGA(resolve, reject) {<br>        if (getGAId())<br>            resolve(getGAId());<br>        else if (timeout &amp;&amp; (Date.now() - start) &gt;= timeout)<br>            reject(new Error(&quot;timeout&quot;));<br>        else<br>            setTimeout(waitForGA.bind(this, resolve, reject), 30);<br>    }<br>}<br>  <br>var theIframe = jQuery(&quot;iframe[src*=&#39;target_string&#39;]&quot;);  <br> <br>// This runs the promise code<br>ensureGAIsSet(timeout).then(function(){<br>    if (jQuery &amp;&amp; !jQuery(&quot;iframe[src*=&#39;&amp;consent&#39;]&quot;).length) theIframe.attr(&quot;src&quot;,theIframe.attr(&quot;src&quot;)+&quot;&amp;_ga=&quot;+getGAId() + &quot;&amp;consent={{Consent grabber}}&quot;); <br>    else if (jQuery &amp;&amp; jQuery(&quot;iframe[src*=&#39;&amp;consent&#39;]&quot;).length) theIframe.attr(&quot;src&quot;, theIframe.attr(&quot;src&quot;).replace(/&amp;consent=.*/,&quot;&amp;consent={{Consent grabber}}&quot;));<br>});</pre><p>The tag is three-sided, let’s look to each one of those:</p><ol><li>The “get GA ID” part defines a pretty common function (you can find several versions of it online) to extract the GA cookie ID from the parent page</li><li>The “promise code” part leverages the new ES6 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise syntax</a> for implementing async programming in JavaScript. This is basically the successor of callbacks and it can be used, here, in place of the old setInterval logic. In short, this promise code waits till a timeout fires (that you can set) looking for the “getGAId” returning valid; if so, it “resolves” executing what’s coded inside the “then” method. In this case, the “then” code will be the enrichment or update of iframe’s URL with GA ID and consent parameters.</li><li>The final “runs” part is the execution one. If the promised “ensureGAIsSet” function is resolved (the “then” code), it appends the GA ID and the consent code to the iframe’s URL as, respectively, the “_ga” and the “consent” parameters. Please take two things into consideration here: this part takes advantage of jQuery library to speed up the coding process, especially the iframe targeting that happens both at start (jQuery(“iframe[src*=’target_string’]”) in my case) and at consent update (jQuery(“iframe[src*=’&amp;consent’]”)). The second thing is about the consent update itself, as this tag is meant to be fired both on parent page load and on the consent update event. In this way, if the user changes consent preferences while staying in the iframe page, the iframe URL will be updated with the new consent, and the iframe itself reloaded. * That’s why, in the first part of this article, I wrote: “A custom HTML tag […], preferably on your Consent Management Platform’s event for consent update”. The CMP’s update event is usually available on both page load, and consent preferences change. This should be the trigger for this tag.</li></ol><p><strong>3 — The RegEx Table variables, for consent reading inside the iframe</strong></p><p>The iframe is now loaded (or reloaded) with the “consent” parameter, but we need to read it and to decode it, creating the default Google Consent statuses for the iframe’s tags. This is done via two RegEx Table variables, one for each consent statuses (if you need more status types, you’ll have more than two of those). This is how they all look like (I take “analytics_storage” as the only example):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_M90z6J2BaNPhJ-0" /></figure><p>This storage will be set to granted if the “consent” parameter, coming from the parent page, equals “101” or “111”, otherwise it will be denied. Set the default value according with your needs. Please note the input {{Variable on consent param}} should be any URL-query-type variable that reads the “consent” parameter appended in the iframe’s source.</p><p><strong>4 — The iframe “Default consents” tag</strong></p><p>The final step to make the iframe work with the parent page’s consents, is to create a Default consent tag, triggered on “Consent Initialisation” event, that takes advantage of the RegEx Tables I’ve just described. This is easily accomplished through Simo Ahava’s template, as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eyPF4lRAqgqsz09h" /></figure><p>And that’s it! Now all the iframe’s tags will benefit from Google Consent mode based on parent page last consents (and the Google Analytics tags will obviously benefit from the “_ga” ID value we also appended in the iframe source URL). It’s easy but important to say the parent page and the iframe should share the same GTM container.</p><p>Thanks for reading and, if you need, just send me a message or a comment here below. Happy analytics !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d44d7f584a40" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sharing Google Consent with iframes (part 1)]]></title>
            <link>https://medium.com/@riccardo.malesani/sharing-google-consent-with-iframes-part-1-9e00600b68ff?source=rss-a543d4c33792------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e00600b68ff</guid>
            <category><![CDATA[google-tag-manager]]></category>
            <category><![CDATA[google-analytics]]></category>
            <category><![CDATA[web-analytics]]></category>
            <category><![CDATA[iframe]]></category>
            <category><![CDATA[iframe-embed]]></category>
            <dc:creator><![CDATA[Riccardo Malesani]]></dc:creator>
            <pubDate>Tue, 12 Mar 2024 21:24:42 GMT</pubDate>
            <atom:updated>2024-03-12T21:24:42.069Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VTICafwXiiXrklhUBlyH0w.png" /></figure><p>This article is based on the one I posted here: <a href="https://medium.com/@riccardo.malesani/fetching-the-google-last-consents-1466867bd22f">fetch the most recent status of Google Consent storages</a>, from a website page. My solution hasn’t come into play….until few days ago, when I had the opportunity to use it.</p><p>The context is one of the worst we Analytics Developers can have to work with, the <strong>cross-site iframe</strong> (nightmare!). As you probably know, the different origin of this kind of embedded contents is disliked by modern browsers, making the data consistency between parent and child windows very hard. However, this is not an article on this appalling topic (Simo Ahava took courage and wrote <a href="https://www.simoahava.com/analytics/cookieless-tracking-cross-site-iframes/">this</a> great post about it), this article describes <strong>why and how to pass the most recent Google Consent Mode status </strong>(for analytics_storage and ad_storage, only)<strong> to the iframe itself</strong>.</p><p>Why ? Let’s start here. My iframe was part of the <strong>conversion journey,</strong> the final and most important part, indeed. It includes a lead generation form. The iframe is on a third-party domain but luckily <strong>it needed no persistence</strong> of Google Analytics identification (it’s a single-form-page)*, so I just had to append the required identifiers to the iframe source URL, without cookies, to keep data consistency between the parent website and the iframe itself (if your iframe includes multiple pages, you need another way to make it work, and this article won’t suit you* — go back to Simo Ahava’s post I linked above). Ok but…<strong>why Google Consent ?</strong></p><p>Because my iframe is part of the same Google Tag Manager setup, active in the parent website, and the conversion tags firing in it (Google Analytics and Google Ads) <strong>should inherit the most recent consent status of analytics_storage and ad_storage</strong> (in my case). In this way, the tags will behave according with the consents the user sets before entering the iframe:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cQSVRGbNHCFjdgmA" /></figure><p>How? You can leverage the common GTM setup building the following main elements (in priority order):</p><ol><li>A <strong>custom JavaScript variable</strong> that: a) makes use of my <a href="https://medium.com/@riccardo.malesani/fetching-the-google-last-consents-1466867bd22f">consentStatus function</a> to fetch the last consents in the page which includes the iframe, b) based on consentStatus outputs, it defines an aggregated value (e.g “111”) that will be assigned to the GET parameter (e.g “consent”) passed to the iframe source URL. The idea is to aggregate the analytics_storage and ad_storage consents all together, in the same way Google does (e.g. “111” means granted for both).</li><li>A <strong>custom HTML</strong> <strong>tag</strong> that fires in the page with the iframe, preferably on your Consent Management Platform’s event for consent update, and that will handle the appending of additional GET parameters to the iframe source URL. These additional parameters are: “consent”, taking value from the custom variable (1), and “_ga”, essential for keeping data consistency (user and session) between the parent and iframe windows. The “_ga” creation is another interesting topic I will share with you in a future post (it will be on the usage of Promise JS API…). The way you code the parameters appending, in this custom HTML tag, is up to you. I used jQuery because it’s straightforward and existing in my website.</li><li><strong>Two custom RegEx Table variable</strong>s to be used inside the iframe. Their task is to disaggregate the “consent” parameter value (e.g “111”) into the analytics_storage and ad_storage consent statuses (in this example, “granted” for both). These variables will be based on another custom variable (URL — query type) grabbing the “consent” parameter from the iframe source.</li><li>A <strong>Consent Mode tag</strong> (Simo Ahava’s template) set as Default. This tag, to be used inside the iframe as well, will be initiated at the “Consent Initialisation” default trigger, assigning the default statuses to analytics_storage and ad_storage, based on the RegEx Table variables (3). This will be the final step for the Google Consent transfer to the iframe, as this will be set on the parent website consents, and all its tags will behave accordingly.</li></ol><p>There are other minor things you will have to take care of, in GTM, but these are the four main building-blocks you need to make the Google Consent sharing works. I don’t go into details in this article, otherwise it would be longer, so I will post a second part very soon. Thanks for reading and stay tuned !</p><p><em>* As specified on top of the article, these guidelines apply to a “single-page-application” iframe, that doesn’t need persistence of Google Analytics identification (because there is no multiple pages navigation).</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e00600b68ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fetching the Google (last) consents]]></title>
            <link>https://medium.com/@riccardo.malesani/fetching-the-google-last-consents-1466867bd22f?source=rss-a543d4c33792------2</link>
            <guid isPermaLink="false">https://medium.com/p/1466867bd22f</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[google-analytics]]></category>
            <category><![CDATA[web-analytics]]></category>
            <category><![CDATA[consent-mode]]></category>
            <category><![CDATA[google-tag-manager]]></category>
            <dc:creator><![CDATA[Riccardo Malesani]]></dc:creator>
            <pubDate>Tue, 12 Mar 2024 21:16:46 GMT</pubDate>
            <atom:updated>2025-03-09T17:54:40.286Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*adzjAum-ttwmYuVXEXFlZg.png" /></figure><p>This article is about the <strong>Google Consent Mode API</strong> and the viewpoint of a former developer.</p><p>It’s been a while for me on this new technology, having experienced several ways of deployment in connection with different Consent Management Platforms (CMP), obviously delivered via GTM. But this article is not about the Consent Mode implementation. It’s on a requirement you may find yourself with later on, when it’s up and running: how to easily, quickly and surely <strong>fetch the most recent status</strong> of a specific consent storage ?</p><p>When a <strong>consent update</strong> command is fired, either by the CMP itself or by a custom template or event you set, the dataLayer object is filled with related arguments (consent storages), based on the Consent Mode API. This means no custom event, nor custom variables you can easily read from GTM, are available to you. More, this update command could be fired multiple times on the same page: think about a user changing preferences repeatedly or what happens in a <strong>single-page-application</strong>.</p><blockquote><em>how to quickly and surely fetch the most recent status of a specific consent storage ?</em></blockquote><p>This behaviour will result in a “consent update arguments sequence” in the dataLayer (among its other things). Let’s say the “analytics_storage” is denied on first, then updated to granted, then it’s denied again. The same might have happened for “ad_storage” or “personalization_storage” at the same time:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*b86pB3vlwTICravH" /></figure><p>Let’s also say you need to know which is the most recent status of “analytics_storage”. You know it’s in the last “consent update” arguments here, at the very bottom of the sequence, but you cannot retrieve it…don’t believe me? I could have missed something, but there isn’t any Consent Mode API for that, nor a built-in way to read it via GTM variables or similar. I guess for Google it’s not a priority requirement for the users, but what if you need to develop your own logic in GTM for making something happened, based on the last status of a particular Consent Mode storage? That was my requirement, and what follows is my way to achieve it.</p><p>I built a custom JavaScript function, inspired by <a href="https://support.cookiebot.com/hc/en-us/articles/360018413380-Checking-if-Consent-Mode-is-properly-implemented">this article</a> (thanks CookieBot) and called it <strong>consentStatus</strong>, that “stringifies” and loops the dataLayer, looking for the “consent update” members. When the wanted Google Consent Mode storage (the “analytics_storage” in my example) is found, the function creates an array of all its statuses in the sequence, and finally returns the last of them. Here it is — if you like, give it a try:</p><pre>function consentStatus(storage) { <br> var El = window[&quot;dataLayer&quot;],<br>     List = [],<br>        Stringify = function(obj) {<br>         var seen = [];<br>         var output = JSON.stringify(obj, function(key, value) {<br>            if (typeof value === &quot;object&quot; &amp;&amp; value !== null) {<br>              if (seen.indexOf(value) !== -1) return;<br>              seen.push(value);<br>            }<br>            return value;<br>         });<br>         seen = null;<br>         return output;<br>        };    <br>    for (var i in El) { <br>        if (Stringify(El[i])) var Value = Stringify(El[i]).replaceAll(/\&quot;\d{1,}\&quot;:/g, &quot;&quot;);<br>        if (Value.match(/(&quot;consent&quot;,&quot;update&quot;|&quot;(h|value)&quot;\:)/)) { <br>      var Reg = new RegExp(storage + &#39;_storage&quot;:&quot;([^&quot;,]+)&#39;);<br>      if (Value.match(Reg)) List.push(Value.match(Reg)[1]);<br>       <br>     }<br>        <br>    } <br>    return List[List.length-1];<br>}</pre><p>Of course you have to define this function in the most useful fashion, depending on how your website or application is built and how the pages are loaded. In my case, I included it in another HTML tag I always fire through GTM, but there are plenty of options, based on your final requirement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/0*maMcPv6VyLa1z-et" /></figure><p>How to use it ? Simply call it with the storage name you want the most recent consent status for. Just remember to omit the “_storage” part. You will pass “analytics” in place of “analytics_storage”, or “personalization” in place of “personalization_storage” (you can use it for the new Consent Mode v2 storages, as well).</p><p>That’s all! Thanks for reading till here and I hope this can help you with the Google Consent (missing) API. If you have suggestions, improvements or questions, just leave a comment below or contact me, I will be happy to catch up.</p><blockquote><em>what if you need to develop your own logic in GTM for making something happened, based on the last consent status of a particular Consent Mode storage?</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1466867bd22f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>