У меня есть этот код, украшающий URL-адреса с помощью cookie Google Analytics на моей веб-странице.
var tracker = window[window.GoogleAnalyticsObject].getAll()[0];
new window.gaplugins.Linker(tracker).decorate("http://www.toto.com");
Возникает ошибка:
window [window.GoogleAnalyticsObject].getAll не является функцией
window.gaplugins не определено
Подобно тому, как Google Analytics загружает плагин асинхронно, я предполагаю, что функции getAll()
и gaplugins.linker
еще не объявлены. Я не могу дождаться DOM, поэтому я хотел бы принудительно синхронизировать загрузку GA-плагина.
Спасибо за вашу помощь
Используя здесь документацию (см. Eduardo comments), мы могли бы отправить сообщение дочернему iframe:
<iframe id="destination-frame" src="https://destination.com"></iframe>
<script>
ga('create', 'UA-XXXXX-Y', 'auto');
ga(function(tracker) {
// Gets the client ID of the default tracker.
var clientId = tracker.get('clientId');
// Gets a reference to the window object of the destionation iframe.
var frameWindow = document.getElementById('destination-frame').contentWindow;
// Sends the client ID to the window inside the destination frame.
frameWindow.postMessage(clientId, 'https://destination.com');
});
</script>
И в стороне iframe:
window.addEventListener('message', function(event) {
// Ignores messages from untrusted domains.
if (event.origin != 'https://destination.com') return;
ga('create', 'UA-XXXXX-Y', 'auto', {
clientId: event.data
});
});
Вместо того, чтобы принудительно выполнять синхронизацию, лучшим вариантом является использование функции обратного вызова для выполнения кода.
Как это:
(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-XXXXXX-1', 'auto');
ga('send', 'pageview');
ga(function(){
// Code in here will only run after ga is loaded.
window.tracker = window[window.GoogleAnalyticsObject].getAll()[0];
new window.gaplugins.Linker(tracker).decorate("http://www.toto.com");
})