Skip to content

Instantly share code, notes, and snippets.

@rxnlabs
Last active August 11, 2020 16:16
Show Gist options
  • Save rxnlabs/ada3f57be8a560368e01 to your computer and use it in GitHub Desktop.
Save rxnlabs/ada3f57be8a560368e01 to your computer and use it in GitHub Desktop.
JS - Call and execute javascript functions by names by passing the function name as a string. Use case: Pass an event to ALL Google analytics properties on a page.
//http://stackoverflow.com/questions/359788/how-to-execute-a-javascript-function-when-i-have-its-name-as-a-string
// http://www.sitepoint.com/call-javascript-function-string-without-using-eval/
function executeFunctionByName(functionName, context, args) {
var args = [].slice.call(arguments).splice(2);
var namespaces = functionName.split(".");
var func = namespaces.pop();
for(var i = 0; i < namespaces.length; i++) {
context = context[namespaces[i]];
}
return context[func].apply(this, args);
}
// Get the name of the Google Analytics object in case it was renamed by a plugin or something
// @link https://developers.google.com/analytics/devguides/collection/analyticsjs/renaming-the-ga-object
executeFunctionByName(window.GoogleAnalyticsObject, window, function(){
var trackers = executeFunctionByName(window.GoogleAnalyticsObject+".getAll", window);
for(var i =0; i < trackers.length; i++) {
var name = trackers[i].get('name') + '.send';
executeFunctionByName(window.GoogleAnalyticsObject, window, name, 'event', {
'eventCategory': 'event-category-here',
'eventAction': 'event-action-here',
'eventLabel': 'event-label-here',
'eventValue': 'event-value-here (change this into an actual number)'
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment