Hemanth.HM

A Computer Polyglot, CLI + WEB ♥'r.

Portal Communication

| Comments

Portals takes the best from SPA and MPA to provide users with a top level portal browsing context which can embedded in an HTML document.

A portal is similar to an iframe, in that it allows another browsing context to be embedded. However, the portal browsing context hosted by a portal is part of a separate unit of related browsing contexts. The user agent is thus free to use a separate event loop for the browsing contexts,even if they are same origin-domain.

At times we would want to communicate with the intial host and the portal and vice versa, it can be easily achived with the below:

In the host:

1
2
3
4
5
6
const portal = document.querySelector('portal');
portal.activate({data: {foo: "bar"}}).then(() => {
  window.portalHost.onmessage = evn => {
     console.log(e.data); // data from the portal
  }
});

We can also get other information from the event:

1
2
3
4
5
6
7
8
9
10
11
12
{
      origin: evn.origin,
      data: evn.data,
      sourceIsPortalHost: evn.source === window.portalHost,
      gotUserActivation: !!evn.userActivation,
      userActivation: {
        isActive: evn.userActivation && evn.userActivation.isActive,
        hasBeenActive: evn.userActivation && evn.userActivation.hasBeenActive
      }
};

// ^ from WPT

In the portal:

1
2
3
4
5
6
window.addEventListener('portalactivate', (evt) => {
    let predecessor = evt.adoptPredecessor();
    evt.data
    predecessor.postMessage("data", "*");
  // ^ predecessor would be an instanceof HTMLPortalElement
});

With portal.activate we can basically pass the {data} to the portal on activation and the portal shall receive this data in the event object of the portalactivate callback.

evt.adoptPredecessor() will provide context to the originator of the portal and portalHost is exposed if the window has a portal browsing context.

Comments