all files / src/shared/ utils.js

74.36% Statements 29/39
66.67% Branches 10/15
83.33% Functions 10/12
74.36% Lines 29/39
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 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 8925×     113×       113×                                     40× 40× 34×                           25×                                                
export const DEBUG_QUERY_PARAM = 'tracking-opt-in-debug';
 
export function isParameterSet(param) {
    return window.location.href.indexOf(`${param}=true`) !== -1;
}
 
export function debug(label, ...args) {
    Iif (isParameterSet(DEBUG_QUERY_PARAM)) {
        console.log(`[DEBUG] ${label}: `, ...args);
    }
}
 
export function getUrlParameter(paramName) {
    const paramList = window.location.search.slice(1).split('&');
    let paramValue = null;
    paramList.forEach((param) => {
        Iif (param.length > 0) {
            const keyValue = param.split('=');
            if (keyValue[0] === paramName) {
                // May return undefined
                paramValue = keyValue[1];
            }
        }
    });
    return paramValue;
}
 
export function parseUrl(url) {
    const parser = document.createElement('a');
    parser.href = url;
    return parser;
}
 
export function getCookieDomain(hostname) {
    const parts = hostname.split('.');
    if (parts.length < 2) {
        return undefined;
    }
 
    let cookieDomain = `.${parts[parts.length - 2]}.${parts[parts.length - 1]}`;
    // These exceptions require a third part for a valid cookie domain. This isn't
    // a definitive list but rather the most likely domains on which Fandom would
    // host a site.
    const exceptions = [
        '.co.jp',
        '.co.nz',
        '.co.uk',
    ];
    if (exceptions.indexOf(cookieDomain) >= 0) {
        cookieDomain = `.${parts[parts.length - 3]}${cookieDomain}`;
    }
 
    return cookieDomain;
}
 
const cachedJson = {};
 
export function getJSON(url, useCache = true) {
    Iif (useCache && cachedJson[url]) {
        return Promise.resolve(cachedJson[url]);
    }
 
    return fetch(url)
        .then(response => response.text())
        .then(responseText => {
            let response;
            try {
                response = JSON.parse(responseText);
                cachedJson[url] = response;
            } catch (e) {
                response = null;
            }
 
            return response;
        })
        .catch(() => {
            throw new Error(`Cannot fetch: ${url}`);
        });
}
 
export function loadScript(url, options) {
    const element = document.createElement('script');
    element.src = url;
    Object.keys(options).map((key) => {
        element.setAttribute(key, options[key])
    });
    document.body.appendChild(element);
}