1

I am writing a chrome extension that defines a custom element. I am using the webcomponents library (documentation here) to polyfill my custom element.

If I call the function in my custom element I get an Uncaught TypeError: ... is not a function error. What am I doing wrong?

background.js

class CustomElement extends HTMLElement {
    constructor() {
        super();
    }

    foobar() {
        console.log("foobar!");
    }
}

// Define the new element
customElements.define('custom-element', CustomElement);

const test = document.createElement("custom-element");
test.id = "test";

// works
test.foobar();

// doesn't work
$("#test").get(0).foobar();

// doesn't work
document.getElementById("test").foobar();

Manifest.json

{
  "name": "Test",
  "version": "1.0",
  "description": "Test",
  "browser_action": {
    "default_title": "Test",
    "default_popup": "html/popup.html"
  },
  "content_scripts": [ {
    "js": [ "scripts/jquery-3.3.1.min.js", "scripts/background.js", "scripts/webcomponents-bundle.js" ],
        "matches": ["<all_urls>"]
  }],
  "manifest_version": 2
  }

If I open the Chrome console and try to find my element/call foobar() there, it also doesn't work.

Moose
  • 41
  • 3
  • I think Web Components expect your functions being available from the main page context but your class is defined in the content script which runs in its own isolated world. Either [Insert code into the page context](//stackoverflow.com/a/9517879) or - instead of inserting your custom components into **all pages** - put your UI inside an iframe exposed in *web_accessible_resources* so it runs in its own environment (there are tutorials for this approach). P.S. background.js is a bad and misleading name since it usually means a background script that runs in a hidden background page. – wOxxOm Mar 30 '19 at 13:49

0 Answers0