Giter Site home page Giter Site logo

dp6 / analytics-helper Goto Github PK

View Code? Open in Web Editor NEW
20.0 35.0 15.0 1.3 MB

A library meant to assist during an Google Analytics implementation

Home Page: https://dp6.github.io

License: MIT License

JavaScript 79.69% HTML 20.31%
google-analytics analytics-helper google-tag-manager gtm ga webanalytics objeto compatibilidade suporte

analytics-helper's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

analytics-helper's Issues

Problemas no "analyticsHelper.getDataLayer" quando a chave é "null"

O GTM, por si só, possui um bug onde, se a chave "pai" for null, a função google_tag_manager[ID].dataLayer.get executará com erro:

image

Precisamos adicionar um try { } catch () {} ao redor dessa função, retornando undefined no catch. Não precisamos realizar maiores tratamentos, pois é esperado que retorne "undefined" nesse caso.

Hit Callback não funcionando corretamente

A função atual é:

function() {
return function(){
analyticsHelper.internal._sentPageview = true;
while(analyticsHelper.options.eventQueue.length){
analyticsHelper.event.apply(analyticsHelper, analyticsHelper.options.eventQueue.shift());
}
};
}

E a função ajustada pelo Paulo é

function() {
return function(){
analyticsHelper.internal._sentPageview = true;
while(analyticsHelper.internal._eventQueue.length){
analyticsHelper.event.apply(analyticsHelper, analyticsHelper.internal._eventQueue.shift());
}
};
}

Extrair o objeto "Options" para uma variável do GTM

Muitas vezes desejamos alterar algumas opções do Helper, como modo debug ou nome do Helper, com o método atual sendo chamar a função analyticsHelper.init() com as novas opções. Aproveitar a variável do tipo "JS" do GTM para as opções evitaria ter que chamar esse método ou modificar o fonte do helper, facilitando o uso.

Retornar um Atributo de um Elemento

Seria interessante se no helper interno do wrap, tivesse uma função para retornar um atributo de um determinado elemento, por exemplo:

helper.wrap(this).attr('name'); e retornaria o valor do nome do elemento.

Helper sobrescrevendo propriedades internas

O problema:

Em alguns casos como quando o template de pageview e a tag de Helper rodam paralelamente, existe a possibilidade do disparo acontecer mais rápido que o carregamento do Helper, causando reset nas propriedades internas. O mesmo ocorre quando alguma tag coloca como dependência o Helper.

A Solução:

A melhor solução é a validação se o helper já foi carregado. Só instanciando quando não houver sido instanciado anteriormente, além de colocar o helper como dependencia do template de pageview. Além disso é necessário configurar a tag do Helper como once per page.

Exemplo do código:

function expose() {
  if (!window[options.helperName]) {
    window[options.helperName] = {
      internal: internal,
      init: init,
      pageview: pageview,
      event: event,
      sanitize: sanitize,
      getDataLayer: getDataLayer,
      cookie: cookie,
      getKey: getKey,
      safeFn: safeFn,
      fn: fn,
    };
  };
}

Explicar como configurar o GTM

Existem algumas configurações que devem ser feitas no GTM para que a implementação funcione.

Por exemplo: é necessário configurar o hitcallback do pageview do GA para que a eventQueue funcione, isto não é mencionado na documentação atual.

O arquivo README-GTM-CONFIG.md está vazio, imagino que o objetivo dele seria explicar estes detalhes.

Closest retornando Array

Seria mais prático que ele retornasse um wrap dos elementos encontrados.

Exemplos de casos

Atualmente:

  // Necessário inserir o retorno do closest em um novo wrap
  helper.wrap(helper.wrap('a').closest('div')).text()

Ideal:

  // Acessar diretamente a função text do retorno do closest
  helper.wrap('a').closest('div').text()

Seletores baseados na tag body

Na documentação, não há uma especificação de como montar um seletor partindo de body, o que é indicado uma vez que algumas tags podem ser dinâmicas e apenas serem criadas depois da Janela Carregada, por exemplo.

Um exemplo de função se baseando no body seria:
analyticsHelper.safeFn('Nome da Tag', function (helper){
helper.on('change', '.seletor', function () {
//sua função
}, 'body');
});

Erro no exemplo da função wrap()

No exemplo:

// Múltiplos elementos
analyticsHelper.safeFn('Nome da Tag', function(helper){
  var urls = helper.wrap('a');
  console.log(urls); // Array de nodes a.
});

Este console.log printaria o objeto wrap e não o array. Para printar o array, o exemplo seria o seguinte:

// Múltiplos elementos
analyticsHelper.safeFn('Nome da Tag', function(helper){
  var urls = helper.wrap('a');
  console.log(urls.nodes); // Array de nodes a.
});

Necessário flag para analyticsHelper.event()

Em alguns casos, foi necessário enviar o evento mesmo sem pageview, facilitaria se houvesse como enviar uma flag para que este evento específico não precisasse entrar na fila e sim disparar direto, mesmo sem pv.

Adequação para regras de cookies (SameSite)

Acrescentar no helper.cookie a opção do samesite

Referência da MDN

Mensagens de erro relacionadas a cookies:

Cookie “myCookie” rejected because it has the “SameSite=None” attribute but is missing the “secure” attribute.

This Set-Cookie was blocked because it had the "SameSite=None" attribute but did not have the "Secure" attribute, which is required in order to use "SameSite=None".

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this 💪.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


The push permission to the Git repository is required.

semantic-release cannot push the version tag to the branch master on remote Git repository with URL https://[secure]@github.com/DP6/analytics-helper.git.

Please refer to the authentication configuration documentation to configure the Git credentials on your CI environment and make sure the repositoryUrl is configured with a valid Git URL.


Good luck with your project ✨

Your semantic-release bot 📦🚀

Permitir que SafeFn retorne o valor da função interna

Eu gostaria de ser capaz de aproveitar a segurança do SafeFn para fazer operações perigosas, nas quais eu gostaria de retornar o valor para a função mãe.

Exemplo:

1 - Diretamente
var imgName = analyticsHelper.safeFn('Função', function(helper) {
return helper.wrap('img').nodes[0].src.split('/').pop();
});

2 - Indiretamente
var getImageName = analyticsHelper.safeFn('Função', function(helper) {
return helper.wrap('img').nodes[0].src.split('/').pop();
}, { immediate: false });
var imgName = getImageName();

Replicar a coleta para o GA4

Incluir uma opção de duplicar a coleta do helper.event (e helper.pageview em alguns casos) para o GA4.
Por ex:

  • Replicar a coleta de ecommerce, transformando a ação (ecommerce.[action]) no nome do evento do ga4 e mandando o objeto items para a camada de dados (podemos aproveitar o template do Simo ou pelo menos parte do código);
  • Replicar a coleta de eventos de interação enviando um evento: "interaction", com os parâmetros category, action e label.

Utilização de variável GA Settings

No container template, as Tags de UA Analytics possuem configurações do Google Analytics distintas. A melhor forma de configurar o GA no entanto, seria através da utilização de uma variável de configuração do GA chamada GA Settings.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.