2

I'm writing a Chrome Extension and I'm attempting to use the WebComponents API to load a singleton customized built-in elements which represent a modal inhertited from <div> loaded in the content script.

My modal custom element looks like this:

// sactModal.ts
export class SactModal extends HTMLDivElement {
  private static instance: SactModal;

  // more private properties

  constructor() {
    super();
  }

  // more public methods
}

In my contentScript.ts I register/define the element and then attempt to add it to the document:

// contentScript.ts
import { SactModal } from "../components/modal/sactModal";

window.customElements.define(
   "sact-modal",
   SactModal,
   { extends: "div" }
);

const modal = document.createElement("sact-modal");
document.body.appendChild(modal);

However, I get an error in Chrome dev tools about customElements being undefined:

Uncaught TypeError: Cannot read properties of null (reading 'define')

enter image description here

So I read up about it and I believe that I'm missing some depenedencies and need to use a polyfill. I believe that the right one that would port the new API into my extension is webcomponents So I attempted to use it as instructed:

npm install @webcomponents/webcomponentsjs

And imported it into the contentScript:

import "@webcomponents/webcomponentsjs/webcomponents-bundle.js";

In this case, the contentScript doesn't load at all.

I also attempted following the instructions in this answer but the contentScript doesn't load in this case either...

I'm pretty much at a dead end and will probably need to revert to plain-old JavaScript and use Document::createElement to create my custom elements but wanted to know if anyone got this working!

Ko Ga
  • 856
  • 15
  • 25
  • 1
    You can move your script to the page's context where `window.customElements` is defined, [here is how you can do that](https://stackoverflow.com/q/9515704/1552587) – Titus Oct 16 '22 at 10:16

0 Answers0