skip to Main Content

I have code like this, which selects a specific meta tag from the document. What I’m expecting from this code is to select and fetch the first tag out of the many tags in the head.

This code has been working fine until now, but something happened to select the meta tag inside the iframe’s shadowDOM instead. As far as I know, the iframe works independently and is not accessible, so why would I want to access it?

The querySelector is looking for the first element, so even if I had access to the iframe, wouldn’t the element in the head be the first?

const getDisplayLocation = () => {
  return window.document.querySelector('meta[name="temp_role"]').content;
};

Actually I modified the code to get access to the document.head, but I don’t know why I was able to access the iframe, shouldn’t it only be accessible through the contentWindow?

2

Answers


  1. You ca use window.top to get the main window

    window.top.document.querySelector('meta[name="temp_role"]');
    
    Login or Signup to reply.
  2. You can ensure that your code only selects meta tag from the main document’s head (i assume your iframe is in the body):

    const getDisplayLocation = () => {
          const metaTag = document.head.querySelector('meta[name="temp_role"]');
          return metaTag ? metaTag.content : null;
    }
    

    Indeed the querySelector selects the first matching element. however, I assume that your meta is dynamically inserted or changed.
    So that the script might be running at a point where the main document’s head doesn’t have the meta tag yet.
    I’d put some conditional console.log to figure out the exact issue.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search