Skip to content

hasLocalStorageKey — GTM Variable Template for GTM

VARIABLES › GTM
hasLocalStorageKey EXTENDED GTM

Check whether a specific key exists in localStorage.



Examples

Example 5
CONFIGURATION
Storage key: userSettings
OUTPUT
true

GTM Configuration

This is what you'll see when you open this variable in Google Tag Manager. Hover the icons for details.

Read-only Preview
hasLocalStorageKey
Storage Key
💾 The key to check in localStorage.

Supported formats:
  ✓ String
Input Setup
Input Function (optional)
⚙️ Optional pre-processing function applied to the key before internal logic (e.g., normalize case, add prefix). Internal transformations will still apply afterward.
Result Handling
Output Function (optional)
⚙️ Optional function to apply to the result before returning it (e.g., val => val ? 'Exists' : 'Missing', val => !val for negation). Useful for chaining transformations on the output.


Under the Hood

📜 View Implementation Code
/**
 * Checks whether a given key exists in localStorage.
 *
 * @param {string} data.key - The key to check in localStorage.
 * @param {Function|string} [data.out] - Optional output handler: function to transform result or string with format.
 *
 * Direct-mode specific parameters:
 * @param {Function} [data.pre] - Optional pre-processor function to transform key before checking.
 * 
 * @returns {boolean} True if the key exists in localStorage, false otherwise.
 *
 * @framework ggLowCodeGTMKit
 */

const localStorage = require('localStorage');

const hasLocalStorageKey = function(key) {
    return localStorage.get(key) !== null;
};

const safeFunction = fn => typeof fn === 'function' ? fn : x => x;
const out = safeFunction(data.out);

// ===============================================================================
// hasLocalStorageKey - Direct mode
// ===============================================================================
const applyCast = (castFn, value) => safeFunction(castFn)(value);
const processedKey = applyCast(data.pre, data.key);
return out(hasLocalStorageKey(processedKey));
// ===============================================================================
// hasLocalStorageKey() – Apply Mode
// ===============================================================================
/*
return function(value) {
   return out(hasLocalStorageKey(value));
};
*/


___WEB_PERMISSIONS___

[
  {
    "instance": {
      "key": {
        "publicId": "access_local_storage",
        "versionId": "1"
      },
      "param": []
    },
    "isRequired": true
  }
]