-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtemplate.js
More file actions
50 lines (38 loc) · 1.69 KB
/
template.js
File metadata and controls
50 lines (38 loc) · 1.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/// <reference path="./server-gtm-sandboxed-apis.d.ts" />
const getEventData = require('getEventData');
const decodeUriComponent = require('decodeUriComponent');
const encodeUriComponent = require('encodeUriComponent');
const parseUrl = require('parseUrl');
const makeTableMap = require('makeTableMap');
const getType = require('getType');
/*==============================================================================
==============================================================================*/
const pageLocation = getEventData('page_location');
const parsedUrl = parseUrl(pageLocation);
if (!parsedUrl.search) return pageLocation;
const fromTo = makeTableMap(data.customParams, 'from', 'to');
const searchParams = parsedUrl.searchParams;
const newSearchParams = [];
// 'fromKey' is always decoded.
for (const fromKey in searchParams) {
const value = searchParams[fromKey];
let toKey = decodeUriComponent(fromTo[fromKey] || fromTo[enc(fromKey)] || ''); // If the person added it either decoded or encoded.
if (data.skipExisting && searchParams.hasOwnProperty(toKey)) toKey = undefined;
const newKey = toKey ? toKey : fromKey;
getType(value) === 'array' // For parameters that are repeated.
? value.forEach((v) => newSearchParams.push(enc(newKey) + '=' + enc(v)))
: newSearchParams.push(enc(newKey) + '=' + enc(value));
}
return (
parsedUrl.origin +
parsedUrl.pathname +
'?' +
newSearchParams.join('&') +
(parsedUrl.hash ? parsedUrl.hash : '')
);
/*==============================================================================
Helpers
==============================================================================*/
function enc(data) {
return encodeUriComponent(data || '');
}