JavaScript snippet that extracts the hreflang attribute data for a given URL, suitable for browsers like Chrome and Firefox. This snippet will capture the hreflang values and links, organising the data into a CSV file for download.
How to Use
Paste the following JavaScript snippet into the console log. (note, if you have previously never pasted JS into the console log, try typing in "allowing pasting" first)
What it does
The script starts by selecting all link elements in the document that have a rel attribute set to alternate, which are used for specifying hreflang attributes. Then the script iterates over these links, extracting the hreflang value and the URL (href attribute) for each. It then formats this data into CSV format, with Hreflang and URL as the header names.
Example Output
Tested on adidas.co.uk
How to Use
Paste the following JavaScript snippet into the console log. (note, if you have previously never pasted JS into the console log, try typing in "allowing pasting" first)
Code:
(() => {
// Selector for 'link[rel=alternate]' to capture hreflang links
const selector = 'link[rel="alternate"]';
const links = document.querySelectorAll(selector);
// build CSV content
let csvContent = "data:text/csv;charset=utf-8,";
csvContent += "Hreflang,URL\n";
links.forEach(link => {
const hreflang = link.getAttribute('hreflang');
const href = link.getAttribute('href');
csvContent += `${hreflang},${href}\n`;
});
// create a temporary link to download the CSV
const encodedUri = encodeURI(csvContent);
const link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "hreflang_links.csv");
document.body.appendChild(link); // Required for Firefox
console.log("CSV content ready. Click the temporary download link that appears in the bottom of this script output.");
console.log("If the download does not start automatically, click the link manually.");
// trigger the download
link.click();
document.body.removeChild(link); // clean up
})();
What it does
The script starts by selecting all link elements in the document that have a rel attribute set to alternate, which are used for specifying hreflang attributes. Then the script iterates over these links, extracting the hreflang value and the URL (href attribute) for each. It then formats this data into CSV format, with Hreflang and URL as the header names.
Example Output
Tested on adidas.co.uk