(function linksHrefLang() {
var me = {
fn: {
templateHrefFlang: function (href, arrayhrefLangs) {
var html = '<' + 'link rel="alternate" href="' + href + '" hreflang="' + arrayhrefLangs + '" /' + '>';
return html;
},
},
run: function () {
var referenceEl = document.querySelector("html>head"); // obtienes el head de la pagina
if (referenceEl) {
// verificaas que no sea undefined
var href = window.location.href;
//array de todos los hreflags que existen
var arrayHrefLangs = [
"x-default",
"es",
"es-AR",
"es-BO",
//"pt-BR",
"es-CL",
"es-CO",
"es-CR",
"es-EC",
"es-GT",
"es-PY",
"es-PE",
"es-DO",
];
var htmlRefLangElements = [];
//buscando elemento link canonical dentro de la web
var linkCanonicalEl = document.querySelector(
'html>head link[rel="canonical"]'
);
if (linkCanonicalEl) {
linkCanonicalEl.remove();
}
htmlRefLangElements.push('<' + 'link rel="canonical" href="' + href + '"/' + '>');
//buscando elementos links alternate dentro de la web
var linksAlternateEls = document.querySelectorAll(
'html>head link[rel="alternate"]'
);
var arrayHrefLangsWeb = [];
if (linksAlternateEls.length > 0) {
for (var i = 0; i < linksAlternateEls.length; i++) {
var linksAlternateEl = linksAlternateEls[i];
var AttrHreflang = linksAlternateEl.getAttribute("hreflang");
var href = linksAlternateEl.getAttribute("href");
if (AttrHreflang) {
if (/[a-z]/.test(AttrHreflang.substring(3))) {
AttrHreflang = AttrHreflang.substring(0, 3).concat(
AttrHreflang.substring(3).toUpperCase()
);
}
arrayHrefLangsWeb.push({ hreflang: AttrHreflang, href: href });
}
linksAlternateEl.remove();
}
}
//Aca se agregan los links que no estan en arrayHrefLangsWeb, es decir, dentro de la web
for (var i = 0; i < arrayHrefLangs.length; i++) {
var existingHrefLang = arrayHrefLangsWeb.find(function (_) {
_.hreflang == arrayHrefLangs[i];
});
if (!existingHrefLang) {
var url = "";
var pathname = window.location.pathname;
var search = window.location.search;
var hrefLang = arrayHrefLangs[i];
var country = hrefLang.substring(3).toLowerCase();
if (hrefLang == "x-default") {
url = "https://" + window.location.host + pathname + search;
} else if (hrefLang == "es") {
url = "https:/www.huggies.com." + "pe" + pathname + search;
} else {
if (country == "br") {
url = "https://www.huggies.com.br" + pathname + search;
} else if (
country == "bo" ||
country == "cr" ||
country == "cl"
) {
url = "https:/www.huggies." + country + pathname + search;
} else {
url =
"https:/www.huggies.com." + country + pathname + search;
}
}
htmlRefLangElements.push(
me.fn.templateHrefFlang(url, arrayHrefLangs[i])
);
} else {
htmlRefLangElements.push(
me.fn.templateHrefFlang(
existingHrefLang.href,
existingHrefLang.hreflang
)
);
}
}
referenceEl.insertAdjacentHTML(
"afterbegin",
htmlRefLangElements.join("\n")
);
} else {
// Log Error
err = "Reference element not found";
console.log(err);
}
},
};
return me;
})().run();