How can we set analytics.js cookies after user confirmation? - javascript

With GDPR coming into force, we wanted to restrict our application from dropping any cookie until the user confirms his/her consent.
To do this, I have disabled the analytics on page load by using the following config.
window['ga-disable-UA-XXXXXXXX-X'] = true;
After user gives consent by clicking on the cookie banner, I have to enable tracking.
Theoretically, I have to enable it by adding the below line after user action.
window['ga-disable-UA-XXXXXXXX-X'] = false;
and run the analytics.js again which i am not sure how to.
I have found a solution for the legacy ga.js but not for analytics.js.
Is there any other way of doing this which i am missing?
Any pointers would be appreciated.

What is widely used is the use of a cookie message. This message can be fired by Google Tag Manager or a snippet from a tool (for example Cookiebot) that is hard coded on your website. Since Google Tag Manager does not collect any PII you can use it without any permission. When the cookie message has fired you can collect a cookie when they give explicit permission. Collect this cookie within Google Tag Manager as a variable. When you want to send data for example to Google Analytics (tag) you can set a trigger which has certain constraints. for example send a pageview (tag) when someone hit a pageview (trigger) and has given permission (variable).

Take a look at how Google Tag Manager does it, might help or could even use GTM.
To implement Google Tag Manager on your website:
Copy the following JavaScript and paste it as close to the opening tag as possible on every page of your website, replacing GTM-XXXX with your container ID:
<!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-XXXX');</script>
<!-- End Google Tag Manager -->
Copy the following snippet and paste it immediately after the opening tag on every page of your website, replacing GTM-XXXX with your container ID:
<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-XXXX"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->
Many tag management operations can be achieved by just doing the basic code installation, but if you'd like to have finer grain control over tag events or data, you may want to use some customization using our asynchronous methods.

Related

Changer l'ID Google Tag Manager (GTM) dynamiquement

Context:
We have launched the beta of our event-based in-app messaging SaaS. We want to make a sandbox to allow users to test the tool and validate if it fits their needs.
For this we want to allow our testers to add their GTM ID to be able to play with the product on a fake application.
Do you know a way to send a gtm ID dynamically so that with a single web-app they can each send their own in-app messages from their GTM?
Currently we are looking for solutions and will try to change the GTM ID to a param URL, but have very little hope.
Open to all possibilities

Using Google Tag Manager with Google Analytics to track a Chrome Extension (2020)

I am working on a chrome extension, and I would like to be able to track metrics with google analytics. I believe the easiest way to do that would be through tag manager, and I have found this tutorial that explains how to implement google tag manager in a chrome extension. However, just following this tutorial isn't working for me, and I have a few questions.
Is it possible to track a chrome extension using Google Analytics? If so, I have only seen tutorials using Universal Analytics, but is it possible using Google Analytics 4? It is recommended to start out with GA4 now, and I would like to do that if possible.
How would I set up a data stream? A web data stream requires a valid URL, which doesn't really apply to an extension. I have a separate website that I am working on and I can include that URL, but my goal is to track the extension, not the website.
When debugging in GTM, it now requires you to add a URL on which to debug. My extension runs on amazon.com but when I enter amazon.com as the URL I get a 404, probably because the tracking code doesn’t actually apply to amazon, but to the iframe that is injected when I am on amazon. What would I do here?
I have it set up so that the GTM code is in a separate js file that is injected into the iframe html code at the end of the head tag. I have modified the CSP in the manifest to allow requests to google analytics and google tag manager. And when building the tag in GTM, I set the fields checkProtocolTask to false, page to a custom url, and path to {{Page Path}} as the above tutorial and this SO question have suggested. For now I have my GA account set up with GA4, and I'm using a web data stream. I have the GTM tag as a GA4 configuration and I have made sure I included the correct measurement ID. I'm having a hard time finding any information about using GTM/GA in a chrome extension, and so any answers or suggestions would be greatly appreciated.
Okay, for anyone still wondering how to add Analytics to a Chrome Extension, I've figured it out.
First of all, you have to use Universal Analytics (analytics.js), Google Analytics 4 (gtag.js) will not work. It doesn't handle tasks, and we will need to disable certain tasks in order to send hits. Also, it may be possible to use UA with Google Tag Manager, but after I got so deep into figuring this out I decided it would just be easier for me to implement tracking in the code myself. This video that shows you how to set up a UA property in Google Analytics.
In my code, I created a JavaScript file ga.js, with the typical google analytics tracking code that looks like this:
(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','ga');
ga("create", "UA-XXXXX-X", "auto");
with two slight modifications: add the 'https:' in front of the google analytics url, and of course add your own UA property id.
After that, we have to disable checkProtocolTask by adding
ga('set', 'checkProtocolTask', null);
This disables file protocol checking, which we need because google analytics aborts the hit if it's not originating from an http or https protocol (this is originating from a 'chrome-extension://' protocol). I also found I needed to disable checkStorageTask in the same manner, though I am less sure why I needed to do that. All of the resources I have found say that only the checkProtocolTask needs to be disabled to use GA in a CE. My best guess is because my extension isn't a popup, but an injected iFrame, so the cookie permissions are different. I asked this question about it, but haven't gotten any responses. In order to still track user sessions without the use of cookies, I used localStorage to store the ga clientId, as shown here.
I then linked this javascript file at the bottom of the head section of my html file, and added
"content_security_policy": "script-src 'self' https://www.google-analytics.com; object-src 'self'"
to my manifest.json. And Voila! It's working.
Some last minute notes: I definitely recommend using analytics_debug.js while debugging analytics, and if you are still having trouble figuring out the issue then try setting window.ga_debug = {trace: true}; to get an even more detailed log in the console. Also, when sending pageviews, it is important to include the page in the hit as so: ga('send', 'pageview', '/popup');.
This was an absolute headache to figure out, so I hope this helps someone!

Getting GTM code working on web application

Our company uses a third party service for our career/job site, allowing users to submit applications for job postings. Initially, users land on an external facing platform which integrates nicely with GTM. Within the CMS, you can easily add GTM code to the header and body area. However, once a user clicks 'apply' on a job description, they're redirected to a web application, which is essentially a separate system. Unfortunately, this second system does not allow you to add code to the header or footer. I am, however, able to add code to the "thank you" page which users see when they submit an application.
On the "thank you" page, the only way to insert the GTM code is using a WYSIWYG. You cannot insert the code into the <head>, but you can insert it into the <body>. I know it's not ideal, but it's the only option.
Even though I can get the code to render on the page, it's not working at all. It's not recording pageviews, Google Tag Assistant doesn't see the code, and Google's GTM toolbar doesn't show up when the GTM container is in preview mode.
From what I can tell, the page does not refresh when a user submits an application. Thus, I'm assuming that is the reason why the tag is not working. I've tried using a number of different triggers, based on advice I've read online, but none have solved the issue.
I'm just using the standard GTM code, but I'll post my code below anyways:
<!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','###');</script>
<!-- End Google Tag Manager -->
NOTE: I'm also utilizing the <noscript> code immediately after the <script> code.
It would appear that the site you are trying to inject GTM into, takes steps to prevent you from adding JavaScript into their page.
This is a very common security measure on sites that allow users to add content to pages, as instead of GTM you could add something that attacks their server or place a bitcoin miner on the page.
https://en.wikipedia.org/wiki/Code_injection
Your only solutions to this is to ask your provider to support GTM directly, or if your lucky you may find the <noscript> version does work and that might be enough to meet your requirement.

Can Google Picker API be used to save file from a URL to Google Drive?

I would like to create a website which enables users to save a web file to their Google Drive Account. User has to paste the URL of the file and upon submitting the file will be saved to user's Google Drive account. This website offers such a functionality (not necessarily from Picker API). I would like to replicate it. How it could be done?
Not necessarily the Google Picker API but you may want to try the Save to Drive Button feature of Google Drive API. This feature enables your web site to allow users to save files to their Drive account from an arbitrary URL via their browser. The button is configured with a few attributes in a div tag in the HTML markup, similar to how the +1 button is created.
The simplest way to display a Save to Drive button on your page is to include the necessary JavaScript resource and to add the Save to Drive button tag:
<script src="https://apis.google.com/js/platform.js" async defer></script>
<div class="g-savetodrive"
data-src="//example.com/path/to/myfile.pdf"
data-filename="My Statement.pdf"
data-sitename="My Company Name">
</div>
For more detailed information and examples, please try going through the given link.
Hope that helps! Cheers!

How Can You Embed An iframe IN A Google Search Result Page

For whatever reason, that's not important, i'm trying to combine google shopping with another page via an iframe.
I've tried the approach proposed here, consisting of embedding a google custom search query in an iframe, but google custom search does not allow access to the shopping tab.
I figured, if you can't embed Google, embed yourself in it. So I proceeded to inject some jQuery in the page
var jq = document.createElement('script');
jq.src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(jq);
// ... give time for script to load, then type.
jQuery.noConflict();
clean up the google shopping search results page to what I needed, namely the html inside the div#search
jQuery(function($) {$('#search').show().parentsUntil('body').andSelf().siblings().hide();});
Create an iframe and inject it:
var iframe = document.createElement('iframe')
iframe.src="http://example.com"
iframe.width="100%";
iframe.height="500";
iframe.style="visibility:visible";
document.body.appendChild(iframe)
Only problem is the iframe doesn't load the contents of the page and in turn is blank. If you try the above snippet in any other page, it works. It seems like Google is blocking the iframe from loading. How can I get around that?
Google seems not to work using an iframe... Even if you are not using JS.
What you should use instead is the Google Custom Search API, wich allows you to create a custom search engine.
You just have to enter an example website, change the Option to Search all the web. and remove your entered website again.
To create a custom Search engine you'll need a google account.
Start here.
When I run that code, the following error is reported in my console:
VM259:7 Mixed Content: The page at 'https://www.google.co.uk/?gws_rd=ssl' was loaded over HTTPS, but requested an insecure resource 'http://example.com/'. This request has been blocked; the content must be served over HTTPS.
Changing it to an HTTPS URL:
var iframe = document.createElement('iframe')
iframe.src="https://example.com"
iframe.width="100%";
iframe.height="500";
iframe.style="visibility:visible";
document.body.appendChild(iframe)
… makes it work fine (albeit it tucked behind the logo):
Tnx for #Quentins comment.
UPD:
Embedding code to google website:
In general you can't embed code for page that you don't own.
if user opens your website and open another tab with google or your website opens another tab with google, your website doesn't have access to google website source code/context and you can't affect on google website, because there are completely isolated from each other.
Seems your actions for cleaning results and embedding your iframe in google page you made in your browser console. That changes affect only locally for your browser and doesn't affect for any other users that open google website.
Possible solutions:
Actually, you can embed some code to other pages, but you need to use:
Browser extensions (too complicated, because user need to install your extension for browser)
XSS/other vulnerables (that's almost impossible for google search website)
Embedding google to your page:
You can't embed iframe from google because of x-frame-options header in http response for google.com. There is no good workaround, sorry.
The X-Frame-Options HTTP response header can be used to indicate whether or not a browser should be allowed to render a page in a <frame>, <iframe> or <object>. Sites can use this to avoid clickjacking attacks, by ensuring that their content is not embedded into other sites.

Categories