Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Google tag manager not working on IOS #1433

Closed
CoffiDev opened this issue Apr 25, 2019 · 45 comments
Closed

Google tag manager not working on IOS #1433

CoffiDev opened this issue Apr 25, 2019 · 45 comments

Comments

@CoffiDev
Copy link

The configuration for the tag manager was done by adding something like the following to the index.html of the project:

<!-- Global Site Tag (gtag.js) - Google AdWords: GOOGLE_CONVERSION_ID -->
<script async src="https://www.googletagmanager.com/gtag/js?id=AW-GOOGLE_CONVERSION_ID"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'AW-GOOGLE_CONVERSION_ID');
</script>

Debugging the issue the apparently reason that it isn't working is because when an event is triggered, the app makes a GET request to https://www.google-analytics.com/collect , but on the iOS build inspected through the Safari develop console, that request is never made.

Also, when opening the page from the Safari browser it's working as expected.

The versions are:

"@capacitor/core" : "^1.0.0-beta.17"

"@capacitor/ios": "^1.0.0-beta.19"

"@capacitor/cli": "^1.0.0-beta.19"

Testing from an iPhone 6 running IOS 11.4.1

@jcesarmobile
Copy link
Member

Can you provide a sample project I can use?

@jcesarmobile jcesarmobile added the needs reply needs reply from the user label May 1, 2019
@mlynch
Copy link
Contributor

mlynch commented May 19, 2019

Seems very unlikely that this is a Capacitor issue.

Will re-open if we get more info

@mlynch mlynch closed this as completed May 19, 2019
@naranjamecanica
Copy link
Contributor

I've encountered the same issue. In an app we've made statistics are registered from Android users, but not from iOS users. If I debug the iOS version locally trough the Safari inspector, it is not sending out any requests to Google.

Could it be that the WKWebView is not allowing this? There is no log or warning why this is (not) happening...

To see for yourself you can create an empty capacitor project an add the following HTML and run it on a iOS device.

<html>
<head>
  <meta name="viewport" content="viewport-fit=cover, width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
  <title>GTM Example</title>
</head>

<body>
    <h1>GTM Example</h1>
        
    <script async="" src="https://www.googletagmanager.com/gtag/js?id=UA-44023830-42"></script> 
    <script>function gtag(){dataLayer.push(arguments)}window.dataLayer=window.dataLayer||[],gtag("js",new Date),gtag("config","UA-44023830-42");</script> 
    
    <button id="test-btn">Test button</button>
    <script>
        var btn = document.getElementById('test-btn');
        btn.addEventListener('click', function () {
            dataLayer.push({
                event: 'pageviewCustomEvent',
                pagePath: '/home',
                pageTitle: 'Home'
            })
        })
    </script>
</body>

</html>

I'm willing to help, but right now I don't have any staring point...

@naranjamecanica
Copy link
Contributor

Update: I've found out there are two reasons why it fails:

  1. The capacitor:// protocol is not allowed, in analytics the checkProtocolTask setting can be overridden
  2. The script can't store cookies, set the storage setting to none and using localstorage to store the client id helps.

@bitflower
Copy link

@naranjamecanica Does 2) refer to something like this?
https://gist.github.com/mbaersch/677cfad72592631eea4d385116c91a63

@bitflower
Copy link

bitflower commented Nov 29, 2019

Experiencing the same: no API output traffic to google at all. Basic Google Analytics implementation with their standard integration script as seen above in @naranjamecanica's example.

@capacitor/[email protected]
@capacitor/[email protected]

@jcesarmobile jcesarmobile removed the needs reply needs reply from the user label Jan 15, 2020
@Snake231088
Copy link

Same issue. Any fix? Thx

@Snake231088
Copy link

Ok i've fixed

// cookies -> localStorage
var GA_LOCAL_STORAGE_KEY = 'ga:clientId';
ga('create', 'XXXXXXXXX', {
        'storage': 'none',
        'clientId': localStorage.getItem(GA_LOCAL_STORAGE_KEY)
});
ga(function (tracker) {
        localStorage.setItem(GA_LOCAL_STORAGE_KEY, tracker.get('clientId'));
});

// allow capacitor:// as protocol
ga('set', 'checkProtocolTask', function () { /* nothing */ });

@teslavitas
Copy link

@Snake231088 is it possible to implement a similar fix for a GTM script?

@tyeon95
Copy link

tyeon95 commented Jun 14, 2020

@Snake231088 is it possible to implement a similar fix for a GTM script?

@teslavitas, I've managed to replicate @Snake231088's ga snippet with GTM by using this as a reference: https://www.simoahava.com/analytics/run-google-tag-manager-google-analytics-local-files/

When I log out the values for the client id in localStorage, it's there but it doesn't seem to track events properly on iOS simulator. I've added this under Field to Set under my Base GA Setting variable that's practically referenced by all my GTM tags. I'm assuming there is something missing with setting checkProtocolTask to an empty function. Any help?

@tyeon95
Copy link

tyeon95 commented Jun 15, 2020

@Snake231088 is it possible to implement a similar fix for a GTM script?

I've managed to relay the ga settings from GTM by doing the following:

  1. Create a new GTM variable called Empty function as a Custom Javascript type with the following contents:
function() {
     return function() {}
}
  1. Create a new GTM variable called JS - GetClientId as a Custom Javascript type with the following contents:
function() {
     if (window.Storage) {
       return window.localStorage.getItem('_clientId') || undefined;
     }
     return;
}
  1. Create a new GTM variable called JS - SetClientId as a Custom Javascript type with the following contents:
function() {
     return function() {
       if (window.Storage) {
          window.localStorage.setItem('_clientId', ga.getAll()[0].get('clientId'));
       }
     }
}
  1. Open your GTM variable where you set the Google Analytics Settings type. Go to More Settings > Fields to Set.
    1. Set Field Name to checkProtocolTask with Value as {{Empty function}}
    2. Set Field Name to storage with Value as none
    3. Set Field Name to hitCallback with Value as {{JS - SetClientId}}
    4. Set Field Name to clientId with Value as {{JS - GetClientId}}
  2. Publish, and you're done!

Essentially,
4.i - removes the requirement for the URI protocol to be restricted to http or https.
4.ii, 4.iii, 4.iv - moves the GA client id to be stored on localStorage instead of in the cookie.

@teslavitas
Copy link

@tyeon95 thanks, it works.
I think steps 4.ii - 4.iv did the trick as new GTM code snippets already force usage of HTTPS protocol making 4.i not necessary.

@tyeon95
Copy link

tyeon95 commented Jun 16, 2020

@tyeon95 thanks, it works.
I think steps 4.ii - 4.iv did the trick as new GTM code snippets already force usage of HTTPS protocol making 4.i not necessary.

4.i is only necessary if you're using ionic capacitor for android and ios builds as it the uri of the app in these cases starts with the capacitor protocol capacitor://, and not required if it's only for webapp build

@Cow258
Copy link

Cow258 commented Jul 21, 2020

Ok i've fixed

// cookies -> localStorage
var GA_LOCAL_STORAGE_KEY = 'ga:clientId';
ga('create', 'XXXXXXXXX', {
        'storage': 'none',
        'clientId': localStorage.getItem(GA_LOCAL_STORAGE_KEY)
});
ga(function (tracker) {
        localStorage.setItem(GA_LOCAL_STORAGE_KEY, tracker.get('clientId'));
});

// allow capacitor:// as protocol
ga('set', 'checkProtocolTask', function () { /* nothing */ });

This really work for me.
I'm using ionic webview on iOS.
Also working with Next.js.
Thanks

@smoosh911
Copy link

Anyone get this to work for gtag? I can't mimic what's being discussed.

Here is my code:

const GA_LOCAL_STORAGE_KEY = 'ga:clientId';
localStorage.setItem(GA_LOCAL_STORAGE_KEY, 'ga-key');

gtag('config', 'ga-key', {
'storage': 'none',
'clientId': localStorage.getItem(GA_LOCAL_STORAGE_KEY),
});

gtag('set', {
'checkProtocolTask': function () { /* nothing */ },
});

@nseb
Copy link

nseb commented Aug 25, 2020

+1
I find the solution , for me the solution @tyeon95 not working

@smoosh911
Copy link

+1
I find the solution , for me the solution @tyeon95 not working

Do you mind sharing with me? None of the solutions on this page have worked for me.

@nseb
Copy link

nseb commented Aug 27, 2020

@smoosh911 sorry , I meant : I don't find the solution

@nseb
Copy link

nseb commented Oct 5, 2020

@smoosh911
I Find the solution , new history fragment allows to correct, in fact it is logical because the url we have # with capacitor
image

@smoosh911
Copy link

@nseb i found a solution a while ago. I use GTM with firebase now. It was annoying to have to rewrite but it works pretty well.

@nseb
Copy link

nseb commented Oct 5, 2020

@smoosh911 , can you detail me your solution ?

@smoosh911
Copy link

smoosh911 commented Oct 6, 2020

@nseb There is a capacitor community plugin for Firebase. There is also a library for GTM called react-gtm-module. Create accounts for firebase and gtm, initialize both in their respective libraries in the app, and then they will work together.

Note that GTM will only work within web. Firebase will work on both web and mobile. GTM not working on mobile is due to GA4 not having an easy solution to turning off cookies and disabling the protocol method.

@stanriley
Copy link

stanriley commented Nov 11, 2020

You dont need Firebase for Google Tag Manager to receive events.
Building an Ionic Angular iOS App - Everything works on Web and Android.
This worked for me! Placed right after the TagManager script
gtag('set', {'checkProtocolTask': function(){ /* nothing */ } });

Credit to @ericgopak for showing this.
Not using Firebase.

@smoosh911
Copy link

You dont need Firebase for Google Tag Manager to receive events.
Building an Ionic Angular iOS App - Everything works on Web and Android.
This worked for me! Placed right after the TagManager script
gtag('set', {'checkProtocolTask': function(){ /* nothing */ } });

Credit to @ericgopak for showing this.
Not using Firebase.

@stanriley If you were responding to what I said, you are absolutely right that Firebase is not required for GTM to fire events. I am using Firebase with GTM is all, not that GTM is technically linked or reliant on Firebase to initialize.

About your post, I cannot get your solution to work. You've specified that you have your solution working for Android and Web, does it work for iOS?

@andreas-aeschlimann
Copy link

You dont need Firebase for Google Tag Manager to receive events.

Building an Ionic Angular iOS App - Everything works on Web and Android.

This worked for me! Placed right after the TagManager script

gtag('set', {'checkProtocolTask': function(){ /* nothing */ } });

Credit to @ericgopak for showing this.

Not using Firebase.

I have the same issue and this does not work on iOS for me. Have you made it work on iOS?

@stanriley
Copy link

You dont need Firebase for Google Tag Manager to receive events.
Building an Ionic Angular iOS App - Everything works on Web and Android.
This worked for me! Placed right after the TagManager script
gtag('set', {'checkProtocolTask': function(){ /* nothing */ } });
Credit to @ericgopak for showing this.
Not using Firebase.

I have the same issue and this does not work on iOS for me. Have you made it work on iOS?

Yes. Please do the steps that tyeon95 commented on Jun 15, 2020 for creating GTM variables. Then do the gtag('set', {'checkProtocolTask': function() {/nothing/}}); after the TagManager script.

It works - here's proof - Analytics for PWA, iOS, and Android.
Screen Shot 2021-04-03 at 9 01 41 AM

@stanriley
Copy link

stanriley commented Apr 3, 2021 via email

@andreas-aeschlimann
Copy link

Yes. Please do the steps that tyeon95 commented on Jun 15, 2020 for creating GTM variables. Then do the gtag('set', {'checkProtocolTask': function() {/nothing/}}); after the TagManager script.

It works - here's proof - Analytics for PWA, iOS, and Android.

Nice.

Some confusion here, because for me, Google Analytics looks different – I see different menus on the left.

I wouldn't know where to set built-in variables because I am not using GTM. I created my new «Property» directly from Google Analytics.

@stanriley
Copy link

stanriley commented Apr 3, 2021 via email

@andreas-aeschlimann
Copy link

andreas-aeschlimann commented Apr 3, 2021

Thanks a lot for your helpful input. One problem people (like me) may have is that Google pushes you to use GA without GTM. When creating a new property for tracking on GA, you must check this hidden advanced option:

Screenshot 2021-04-03 at 18 24 53

Now I have followed your instructions and I made the analytics work in the browser and Android again, but it still fails on iOS. I will post screenshots that other users may find helpful as well:

The code in your Ionic application:

Added the following on index.html.

Screenshot 2021-04-03 at 18 19 32

Added the following to AppComponent. (In my case, navigationService.router is a reference to the Angular router.)

Screenshot 2021-04-03 at 18 19 43

Setup on Google Tag Manager website:

The Google Tag.

Screenshot 2021-04-03 at 18 20 05

The configuration of the tag.

Screenshot 2021-04-03 at 18 20 17

The fields to set as described by @tyeon95.

Screenshot 2021-04-03 at 18 20 47

I don't see why it is still not working yet on iOS, but we are probably close. Any help is very welcome! @stanriley is this the way you have setup your GA/GTag account?

EDIT: Having that said, the version of @Snake231088 works well on iOS. But Google says GA is the legacy way, so it would be nice to make it work with GTag.

@smoosh911
Copy link

smoosh911 commented Apr 4, 2021 via email

@andreas-aeschlimann
Copy link

You must disable checkProtocolTask but You can only do this in GA3 (universal analytics). You cannot do this in GA4 (firebase and the new analytics which are event based). There is an outstanding ticket for ga4 to implement checkProtocolTask but it isn’t being worked on yet.

Yeah, it looks that way. It's a shame we have to use the "legacy" product for now. In my opinion Google made a mess by mixing up products. I was using GA for over 10 years and I had no idea about all these new products (GT, GTM, etc.) and about the connection with GA.

I hope that we can do it the new way at some point, though. Thanks for all the constructive posts in this issue!

@vaskea
Copy link

vaskea commented Apr 9, 2021

@andreas-aeschlimann have you managed to get gtm version to work?

Also solution by @Snake231088 is not working for me on ios, can you give me example of your code where it works?
Any help would be appreciated.

@andreas-aeschlimann
Copy link

@andreas-aeschlimann have you managed to get gtm version to work?

Also solution by @Snake231088 is not working for me on ios, can you give me example of your code where it works?

Any help would be appreciated.

As I said, I had to downgrade to normal GA. No GT involved, just the old Analytics script. For now I am quite happy as it is working.

@vaskea
Copy link

vaskea commented Apr 9, 2021

This is my code(added in index.html):

 <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','ga');

        // cookies -> localStorage
        var GA_LOCAL_STORAGE_KEY = 'ga:clientId';
        ga('create', 'UA-XXXXXXXX-X', {
            'storage': 'none',
            'clientId': localStorage.getItem(GA_LOCAL_STORAGE_KEY)
        });
        ga(function (tracker) {
            localStorage.setItem(GA_LOCAL_STORAGE_KEY, tracker.get('clientId'));
        });

        // allow capacitor:// as protocol
        ga('set', 'checkProtocolTask', function () { /* nothing */ });
        ga('send', 'pageview');
    </script>

I have replaced UA-XXXXXX-X with universal property created in analytics console, but I still see no data received when I run the app from iOS.
Using Ionic 5 and Capacitor.
Any ideas what could be the issue? Or how I can debug this

@andreas-aeschlimann
Copy link

andreas-aeschlimann commented Apr 9, 2021

@vaskea you should remove the last line (pageview) and listen to changes on navigation. There are a lot of examples around how to do it. In Angular, you can subscribe to this.router.events.

@vaskea
Copy link

vaskea commented Apr 9, 2021

@andreas-aeschlimann Great thanks, that worked!

@tramert
Copy link

tramert commented Apr 24, 2021

@nseb There is a capacitor community plugin for Firebase. There is also a library for GTM called react-gtm-module. Create accounts for firebase and gtm, initialize both in their respective libraries in the app, and then they will work together.

Note that GTM will only work within web. Firebase will work on both web and mobile. GTM not working on mobile is due to GA4 not having an easy solution to turning off cookies and disabling the protocol method.

@smoosh911 Were you able to get GA4 to work on iOS with Firebase? I have been dissecting & replicating your comments in this thread to no avail.

I am using this Firebase plugin, it seems to initialize on iOS according to the debug logs but it never sends any data.

Any ideas?

Thanks in advance!

@StErMi
Copy link

StErMi commented Aug 27, 2021

Hi there everyone. In the current project, we need to both support Universal Analytics and Analytics v4 (because as far as I get V4 still does not have all the features of the old UA).

I've managed to add support to GA V4 with Firebase Analytics (with this plugin https://github.com/capacitor-community/firebase-analytics).

And now I need to support also Universal Analytics but to be honest, I'm totally lost.

Do I need to use Google global site tags? Do I need to use Google Tag Manager? Are there any capacitor plugin to do that or do I need to find just a react-plugin?

For the GTM I saw this from the Google Documentation I saw this page https://developers.google.com/tag-platform/tag-manager/ios/v5 and my confusion is just growing :D

What do you actually use at the moment?

@BL-marcusrogers
Copy link

Thanks for all the comments on this thread. I battled this for two days before finding this. My app uses AngularFire (along with Ionic) which I thought was the cause of the issue. For anyone else using AngularFire + Ionic and not seeing Firebase Analytic events from iOS (but Auth, Firestore & Functions work on iOS and everything works on desktop and Android), try adding the Capacitor Firebase plugin @tramert mentioned above (https://github.com/capacitor-community/firebase-analytics). Adding that solved the problem for me, no additional configuration required. Thanks again to all who contributed in this thread.

@dodomui
Copy link

dodomui commented Apr 5, 2022

@BL-marcusrogers are you still using Angular/fire analytics to track or do you use the native plugin instead?
One more may I know did you change server.iosScheme to ionic? As I need to have these changes to make it work on Angular/fire 7 + Firebase 9 + Capacitor 3.

@BL-marcusrogers
Copy link

@dodomui I am still using AngularFire analytics, not the native plugin. I have not made any changes to server.iosScheme. My stack is Angular/fire 6 + Firebase 8 + Capacitor 3 (I use ngxs-labs/firestore-plugin which is not yet compatible with Angular/fire 7, so my stack is a version old for now).

@dodomui
Copy link

dodomui commented Apr 24, 2022

@BL-marcusrogers Got it, thanks. I found the issue is because @angular/fire 7

@ChristianR30
Copy link

@nseb There is a capacitor community plugin for Firebase. There is also a library for GTM called react-gtm-module. Create accounts for firebase and gtm, initialize both in their respective libraries in the app, and then they will work together.
Note that GTM will only work within web. Firebase will work on both web and mobile. GTM not working on mobile is due to GA4 not having an easy solution to turning off cookies and disabling the protocol method.

@smoosh911 Were you able to get GA4 to work on iOS with Firebase? I have been dissecting & replicating your comments in this thread to no avail.

I am using this Firebase plugin, it seems to initialize on iOS according to the debug logs but it never sends any data.

Any ideas?

Thanks in advance!

Did you solve the issue?

@ionitron-bot
Copy link

ionitron-bot bot commented Nov 10, 2022

Thanks for the issue! This issue is being locked to prevent comments that are not relevant to the original issue. If this is still an issue with the latest version of Capacitor, please create a new issue and ensure the template is fully filled out.

@ionitron-bot ionitron-bot bot locked and limited conversation to collaborators Nov 10, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests