0

I'm writing a Chrome Extension that injects my tiny app into the webpage. My small app was built with Vue as a Custom Element.

I'm bundling the app into one file called custom-elements.js, and injecting it alongside my content.js:

# manifest.json
"content_scripts": [
  {
    "matches": ["*"],
    "js": [
      "custom-elements.js",
      "content.js"
    ]
  }
],

Now, in my extension I'm using the Range API to hold a reference to a text over elements. My technique is to surround the original text with my custom element.

const originalContents = range.extractContents();

const indicator = document.createElement('overlay-indicator');
indicator.appendChild(originalContents);
range.insertNode(indicator);

This code produces an empty string. Looking inside the DevTools, I see the shadow-root is empty (so the original text is there, but it doesn't render because there is no shadow DOM there).

empty shadow root

I know the custom element is working, because if instead of range.insertNode I'm using just appendChild it renders the custom element:

const testIndicator = indicator.cloneNode()
testIndicator.appendChild(originalContents)
const container = range.startContainer;
container.parentElement.insertBefore(testIndicator, container);

working shadow dom

Also, I tried to create an HTML webpage with the custom-elements.js imported into it as a script, and there it is working.

In summary

It seems using Custom Element is working in Chrome Extension content script, except when using Range.insertNode.

baruchiro
  • 5,088
  • 5
  • 44
  • 66
  • Custom elements use js callbacks for lifetime events, but it won't work in a content script by default because they run in an isolated JS world. You can run the code in the [MAIN world](/a/9517879) but it can be hijacked, spoofed, exfiltrated via standard JS prototypes, so I'd suggest not using a custom element at all. – wOxxOm Feb 19 '23 at 17:41
  • You cannot use custom element in content_script. Check `console.log(customElements), it is null. Check chrome bug [390807](https://bugs.chromium.org/p/chromium/issues/detail?id=390807) – Anil kumar Feb 19 '23 at 19:56
  • @Anilkumar @wOxxOm you can see I managed to use `customElements` in a **content script**, so the question is only why it didn't work when I mounted a `customElement` by `Range.insertNode`. – baruchiro Feb 20 '23 at 07:21
  • `customElements` doesn't exist in `content_script`. It is available in popup window and option page. Why you want to use custom elements ?? – Anil kumar Feb 20 '23 at 07:25
  • @Anilkumar I well known that you need to add a polyfill to enable `customElements` in `content_script` https://stackoverflow.com/a/71782977/839513 – baruchiro Feb 20 '23 at 07:28
  • @baruchiro Can i ask why you want to use custom elements ?? – Anil kumar Feb 20 '23 at 07:30
  • @Anilkumar I want to inject a small `Vue` app into the page – baruchiro Feb 20 '23 at 07:51

0 Answers0