Possible to Change Window/Tab Title using ShadowDOM

320 views Asked by At

I am working on a design for a Chrome Extension. I want to be able to change the title displayed in the tab without altering the real <title /> tag. In the background scripts, you can access the title as a read-only value. Typically, you use a content script and change the actual <title /> tag.

I am experimenting with ShadowDOM to see if this would be an option. The idea being that the ShadowDOM is displayed visually, but is not part of the real DOM and would not impact the real page.

However, in my testing, I can add shadow <head /> and <title /> elements, but they do not change what is shown in the page title. I am guessing this is by design since the browser is probably obtaining these values from the real dom, but I wanted to check to determine if there was a way to have the "shadow title" shown instead?

Given:

<html lang="en">
<head>
  <title>Shadow DOM Example</title>
  <meta charset="UTF-8" />
  <script>
    window.addEventListener("load", function() {

      /** Sanity check, change the content of a part of th body **/

      let realHost = document.getElementById("shadowHost");
      let hostShadow = realHost.createShadowRoot();

      hostShadow.textContent = "Shadow overlay on the body";


      /** Try Creating a Shadow in the Title **/

      let realTitle = document.getElementsByTagName("head")[0].getElementsByTagName("title")[0];
      let titleShadow = realTitle.createShadowRoot();

      titleShadow.textContent = "Created in titleShadow";


      /** Try Creating a Shadow in the Head, then add title **/

      let realHead = document.getElementsByTagName("head")[0];
      let headShadow = realHead.createShadowRoot();

      shadowTitle = document.createElement("title");
      shadowTitle.textContent = "Created in headShadow";

      headShadow.appendChild(shadowTitle);


    }, false);
  </script>
</head>
<body>
  <div id="shadowHost">
    Original Text
  </div>
</body>

I get the following:

Example Output from this test

1

There are 1 answers

0
Supersharp On

With the new, standardized version of Shadow DOM, you should now use attachShadow() instead of createShadowRoot(). Unfortunately you cannot attach a Shadow DOM to the <title> element any more.

So it's not a recommended to use it as it will throw an error in Chrome.

Also, in the <title> specification, only the text content is used as the document title in the UI, so even using the old version of Shadow DOM can't work.