Search code examples
javascriptiframeweb-component

Define Web Component inside IFrame


To enhance my tinyMCE Editor, I would like to add some web components and use them inside the editor. Something similar has been done by others, but with older versions of the editor and javascript, which is not valid anymore.

I am aware, that I have to register the tag inside the editor configuration so this works already and my tag makes it to the dom. The problem is, that given components are not defined inside the editors IFrame.

I was not able to add them to the iframes window, the error message doesn't really tell why though. For Testing purposes, I also added the web component to the regular window, where it works flawlessly.

The IFrame:

<iframe srcdoc="<demo-cmp></demo-cmp>" onload="registerComponent(this)"></iframe>
<demo-cmp></demo-cmp>

The Web Component Definition:

class DemoComponent extends HTMLElement {
  connectedCallback() {
    alert(window.location.href);
  }
}

window.customElements.define('demo-cmp', DemoComponent);

function registerComponent(iframe) {
  // Exception thrown here
  iframe.contentWindow.customElements.define('demo-cmp', DemoComponent);
}

The Error:

Uncaught TypeError: Custom element constructor returned a wrong element

The Fiddle:

https://jsfiddle.net/ynpks9m3/10/


Solution

  • I encountered the same problem when defining web components in IFrame. If can, switch TinyMCE to inline mode to solve it.