Skip to content

Instantly share code, notes, and snippets.

@smhmic
Last active November 8, 2022 15:52
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save smhmic/6b1a8b2c959f8f304458512303f81d16 to your computer and use it in GitHub Desktop.
Save smhmic/6b1a8b2c959f8f304458512303f81d16 to your computer and use it in GitHub Desktop.
Add YouTube JS API support for embedded YouTube videos
<script>(function(){
/*
This script is an alternative to the 'Add JavaScript API support to all YouTube videos'
setting in GTM's YT trigger. GTM's YT trigger will not load the YT API if no videos are
present at page load (it does add the enablejsapi param to dynanmically inserted videos,
but it will not load the YT API js). This script, on the other hand, should work in all cases.
*/
if( window.YT ) return;
var loadYoutubeApiOnce = (function(){
var didIt;
var scriptExists = function(){
var scripts = document.getElementsByTagName("script");
for( i=0; i < scripts.length; i++) {
var src = scripts[i].getAttribute("src");
if (src && (-1 < src.indexOf("//www.youtube.com/iframe_api") || -1 < src.indexOf("//www.youtube.com/player_api")))
return true;
}
};
return function(){
if( didIt || window.YT || scriptExists() ) return (didIt=true);
var j = document.createElement("script"),
f = document.getElementsByTagName("script")[0];
j.src = "https://www.youtube.com/iframe_api";
j.async = true;
f.parentNode.insertBefore(j,f);
didIt=true;
};
})();
var observeDOM = (function(){
var MutationObserver = window.MutationObserver || window.WebKitMutationObserver,
eventListenerSupported = window.addEventListener;
return function(obj, callback){
if( MutationObserver ){
// define a new observer
var obs = new MutationObserver(function(mutations, observer){
if( mutations[0].addedNodes.length )
callback();
});
// have the observer observe foo for changes in children
obs.observe( obj, { childList:true, subtree:true });
//return { stop : function(){ obs.disconnect()} };
}
else if( eventListenerSupported ){
obj.addEventListener('DOMNodeInserted', callback, false);
//return { stop : function(){ obj.removeEventListener( 'DOMNodeInserted', callback, false )} };
}
}
})();
// @func findYoutubeIframes
// @desc Attach our YT listener once the API is loaded. Enables JSAPI if it's not already on the URL. Note: this will cause the Youtube player to reload and "flash" on the page.
var checkForYoutubeIframes = function() {
var iframes, iframe, k, i, l = window.location;
for (iframes = document.getElementsByTagName("iframe"), i = iframes.length; i--;) {
iframe = iframes[i];
if ( ! /youtube(-nocookie)?.com\/embed/i.test(iframe.src))
continue;
if( iframe.hasAttribute( 'data-gtm-fw-yt-listening' ) )
continue;
loadYoutubeApiOnce();
iframe.setAttribute( 'data-gtm-fw-yt-listening', '' );
if( ! iframe.src.match(/[?&]enablejsapi=1(&|$)/) ) {
iframe.setAttribute('data-orig-src', iframe.src );
iframe.src +=
(iframe.src.indexOf('?')>-1?'&':'?') + 'enablejsapi=1'
+'&origin='+encodeURIComponent( l.origin || l.protocol + "//" + l.hostname + (l.port ? ':' + l.port: '' ) )
}
}
}
checkForYoutubeIframes();
observeDOM( document.body, checkForYoutubeIframes );
})()</script>
@henrik-brodtkorb
Copy link

Still works a charm. Thanks! 👍

@josetoledo8
Copy link

I had the GTM YouTube native tracking working only in debug mode. This script works fine for my case, now the tag is firing without debug mode. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment