dp6 / analytics-helper Goto Github PK
View Code? Open in Web Editor NEWA library meant to assist during an Google Analytics implementation
Home Page: https://dp6.github.io
License: MIT License
A library meant to assist during an Google Analytics implementation
Home Page: https://dp6.github.io
License: MIT License
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:
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.
Dependendo da sintaxe utilizada o campo do dataLayer que envia o seletor para o data quality pode não ser enviado. Isso acontece quando utilizada a sintaxe abaixo:
helper.wrap('[seletor]').on('[evento]', function(){})
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());
}
};
}
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.
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.
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 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.
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,
};
};
}
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.
Biblioteca: https://github.com/developit/dlv
Seria mais prático que ele retornasse um wrap dos elementos encontrados.
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()
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');
});
analyticsHelper.sanitize('teste'); // isso causa um bug de undefined, pois o segundo argumento 'options' não existe.
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.
});
@fpzero faz isso?
Precisamos criar a documentação de configuração do GTM para uso do Helper,
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.
Funções como a closest não retornam um objeto helper quando a jQuery está disponível, e sim um objeto jQuery. Isto pode causar erros nos casos em que o ambiente mude sem avisos.
Ambiente sem jQuery:
helper.wrap('a').closest('div').nodes // NodeList []
Ambiente com jQuery:
helper.wrap('a').closest('div').nodes // undefined
Acrescentar no helper.cookie a opção do samesite
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".
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.
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 📦🚀
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();
Para usufruir do versionamento automático é necessário adotar uma convenção para escrita do commit message, optamos pela Angular Commit Message Conventions, por possuir uma categorização simples das alterações.
Optamos por utilizar a biblioteca https://github.com/commitizen/cz-cli, por já utilizamos a stack do Node.JS no projeto.
Os commit precisam ser feitos agora utilizando o comando git cz
Precisamos fazer com que um wrapper que receba um novo wrapper simplesmente retorne ele mesmo.
dar um log('info') sempre que guardar um evento no eventQueue ao invés de falhar silenciosamente
Incluir uma opção de duplicar a coleta do helper.event (e helper.pageview em alguns casos) para o GA4.
Por ex:
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.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.