0

I am dynamically injecting a lit web component into the content script of a Chrome Extension. The component renders, but I'm unable to call a function within the component from the parent page that works outwith the extension environment (but not dynamically injected I might add). The code looks like this:


window.addEventListener('WebComponentsReady', () => { 
    
    const script = document.createElement('script');
    script.setAttribute("type", "module");
    script.setAttribute("src", 'https://localhost:8000/add-to-list.js');
    script.onload = () => {
        console.log('loaded'); 
    };
    const head = document.head || document.getElementsByTagName("head")[0] || document.documentElement;
    head.insertBefore(script, head.lastChild);

    var box = document.createElement('add-to-list');
    box.className = 'comp';
    box.id = 'comp'
    document.body.appendChild(box);

    setTimeout(function () {
        // would be called somewhere else later, but error "productAdded is not a function"
        document.getElementById('comp').productAdded('id', 'success');
    },100);
});

I've injected a webcomponent polymer into the chrome extension, but that does not help "webcomponents-sd-ce.js". The snippet of the manifest is this:

"content_scripts": [
    {
      "matches": [ "<all_urls>"],
      "js": [ "webcomponents-sd-ce.js" ]
    },
    {
      "matches": [
        "https://*/*",
        "http://*/*"
      ],
      "js": [
        "src/inject/inject.js"
      ]
    }
    
  ]

Any advice on why I can't call the function within the component?

Colin Brown
  • 589
  • 1
  • 8
  • 15
  • 1
    The code in `script` element runs in [page context](/a/9517879) so you can't call its functions or vice versa. You'll have to put all the code that needs these functions into page context as well. – wOxxOm Nov 04 '22 at 19:25
  • you could maybe do it via an event. You add en event listener to your lit component. Then on the parent, instead of calling the element function you dispatch a custom event. The lit element listens to this event and runs the function – Boguz Nov 08 '22 at 13:38

0 Answers0