From 30d1848a5d8de190f65602f9709924420c246b2a Mon Sep 17 00:00:00 2001 From: AceGentile Date: Thu, 15 Jun 2023 11:06:08 +0200 Subject: [PATCH] ga4: make "set [string] [object]" requests work gtag set command can have two sets of params: ``` gtag('set', ) gtag('set', , ) ``` the latter doesn't work because of some checks in set() method requiring the first parameter to be always an object. This breaks some user-scoped custom dimensions like this one: ``` gtag('set', 'user_properties', { favorite_composer: 'Mahler', favorite_instrument: 'double bass', season_ticketholder: 'true' }); ``` rif. https://support.google.com/analytics/answer/12370404 --- src/ga4.js | 19 +++++++++++++------ src/ga4.test.js | 19 +++++++++++++++++++ 2 files changed, 32 insertions(+), 6 deletions(-) diff --git a/src/ga4.js b/src/ga4.js index cf6a597..9ebf41e 100644 --- a/src/ga4.js +++ b/src/ga4.js @@ -216,14 +216,14 @@ export class GA4 { } }; - set = (fieldsObject) => { + set = (fieldsObject, args = null) => { if (!fieldsObject) { console.warn("`fieldsObject` is required in .set()"); return; } - if (typeof fieldsObject !== "object") { + if (typeof fieldsObject !== "object" && !args) { console.warn("Expected `fieldsObject` arg to be an Object"); return; @@ -233,7 +233,7 @@ export class GA4 { console.warn("empty `fieldsObject` given to .set()"); } - this._gaCommand("set", fieldsObject); + this._gaCommand("set", fieldsObject, args); }; _gaCommandSendEvent = ( @@ -347,10 +347,17 @@ export class GA4 { }; _gaCommandSet = (...args) => { - if (typeof args[0] === "string") { - args[0] = { [args[0]]: args[1] }; + const newArgs = []; + + if (typeof args[0] === 'string' && typeof args[1] === 'object') { + newArgs.push(args[0], args[1]) + } else if (typeof args[0] === "string") { + newArgs.push(this._toGtagOptions({ [args[0]]: args[1] })) + } else { + newArgs.push(this._toGtagOptions(args[0])) } - this._gtag("set", this._toGtagOptions(args[0])); + + this._gtag("set", ...newArgs); }; _gaCommand = (command, ...args) => { diff --git a/src/ga4.test.js b/src/ga4.test.js index a9042d5..b955ba8 100644 --- a/src/ga4.test.js +++ b/src/ga4.test.js @@ -279,6 +279,25 @@ describe("GA4", () => { page_path: "/home", }); }); + + it("set() with additional params", () => { + // Given + const object = ['user_properties', { + favorite_composer: 'Mahler', + favorite_instrument: 'double bass', + season_ticketholder: 'true' + }]; + + // When + GA4.set(...object); + + // Then + expect(gtag).toHaveBeenNthCalledWith(1, "set", "user_properties", { + favorite_composer: 'Mahler', + favorite_instrument: 'double bass', + season_ticketholder: 'true' + }); + }); }); describe("Reference", () => {