skip to Main Content

I need to access the value of the variable inside the script tag to a meta tag content.

This is the JS Code that i used to get the image variable

<script>
       var pic = document.getElementsByClassName("abc")[0];
       var src = pic.getAttribute('src');
       console.log(src);
</script>

I need to access the src tag to the content of the meta og-image

<meta property="og:image" content="https://example.com/example/**src value should be here**" />

Is it possible? or else what can I do?

2

Answers


  1. Use JavaScript to update the attribute.

    const og_image = document.querySelector("meta[property='og:image']");
    if (og_image) {
        of_image.setAttribute("content", "https://example.com/example/" + src);
    }
    

    I’m not familiar with how the Open Graph protocol works. It may not run JavaScript, so dynamic meta tags won’t work at all. If you’re creating the images dynamically, can’t the same code also generate the meta tags?

    Login or Signup to reply.
  2. UPDATE: Dynamically created or modified Open Graph tags are likely not read by any of the tools that are reading them.

    If you know what image you want on the server, you can set it there too

    <?PHP
      $image = "https://example.com/example/image1.jpg";
      ?>
      ...
      <meta property="og:image" content="<?= $image ?>" />
      ...
      <img class="abc" src="<?= $image ?>"/>
    

    In the unlikely case you can get Google to execute the JS while reading the page, you likely need to use createElement since the meta tag will be read and the image empty if you do it after load.

    So this has to be inline AFTER the image tag

    const src = document.querySelector(".abc").src;
    const meta = document.createElement("meta");
    meta.setAttribute('property','og:image');     meta.setAttribute('content',`https://example.com/example/${src}`); 
    document.querySelector("head").appendChild(meta)
    

    Alternative with document.write

    const src = document.querySelector(".abc").src;
    document.write(`<meta property="og:image" content="https://example.com/example/${src}" />`);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search