Search code examples
javascripthtmlmeta-tags

Dynamic Meta Tags via URL Variables


If you're able to help with this problem, I'd appreciate it as I'm out of my depth.

I have a bunch of meta tags in a HTML header that need to map their content to variables in the URL. For example, if we have this URL:

http://example.com?bofn=Dave&boln=Nate&boem=Pat&botn=Taylor&bstn=Chris&lstn=Rami

We would want the meta tags in the header to read as this:

<meta name="bofn" content="Dave">
<meta name="boln" content="Nate">
<meta name="boem" content="Pat">
<meta name="botn" content="Taylor">
<meta name="bstn" content="Chris">
<meta name="lstn" content="Rami">

From what I've found online this would probably use javascript to function (URLSearchParams and/or location.search?) but I've no clue how to make it happen.


Solution

  • I was able to solve the issue with Pavel's help by replacing the URL with window.location.href:

    <script>
    var str = window.location.href;
    
    // split('?')[1] takes all after '?' (removes http://example.com)
    // split('&') creates array ('bofn=Dave', 'boln=Nate', ...)
    var parts = str.split('?')[1].split('&');
    
    // go through all variables
    for (let i = 0; i < parts.length; i++) {
        // create new HTML element
        var el = document.createElement('meta');
       
        // split key, value
        var keyval = parts[i].split('=');
    
        // set name and content attributes, fill values in
        el.name = keyval[0];
        el.content = keyval[1];
        
        // append meta elements to head
        document.getElementsByTagName('head')[0].appendChild(el);
    }
    </script>