简体   繁体   中英

Can we re-use web components defined in Parent window in an iframe?

We are trying to load few web components into a parent window in our web application and make them available to re-use to the iframes loaded by the parent window, but it doesn't seems to work.

For example:

Javascript loaded in parent window has below web component registered.

Code in file1.js

class MyComponent extends HTMLElement {
  connectedCallback() {
    this.innerHTML = `<h1>Hello world</h1>`;
  }
}
    
customElements.define('my-component', MyComponent);

Html inside another application loaded in an iframe by parent window

<html>
<body>
<my-component></my-component>
</body>
</html>

They are not automatically available similar to defining a global variable in parent window is not automatically in your iframes window object. But if there are no restriction on the iframe and it is allowed to access the parent window, then you can retrieve the constructor of your custom elements ( customElements.get ) and reuse them in your iframe. something like:

// js in your iframe:
const parentWindow = window.parent;
document.querySelectorAll(":not(:defined)").forEach(el => 
  customElements.define(
    el.localName,
    parentWindow.customElements.get(el.localName)
  )
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM