If you would take a look to Stencil Router documentation, you wouldn't find any info neither about open nor close page events, so how we would listen to them? I made a simple library for this purpose.

Let's say we have an application compiled by Stencil which contains more than one page. Now, we want to add Google Analytics on our pages. Let's see how we can implement this goal.

Here's a standard stencil router configuration:

Nothing special, we just provide some props to a stencil-route component, in order to dynamically generate our app-home and app-about components based on History links. More about how to set up a stencil router, check this article.

Now, let's install ip-stencil-route-listener library and make some changes:

npm i ip-stencil-route-listener

After install, we have to add <ip-stencil-route-listener /> component inside of routeRender function of <stencil-route />. Take a look to red lines:

Nothing much! Now each time when you enter or leave a page, the EventListener will trigger pageEnter or pageLeave events. The names of these events talk about their selves.

Take a look at this image:

So, let's add Google Analytics on pageEnter event:

  onPageEnter(e: CustomEvent<LocationSegments>) {
    // This is a Goolge Analytics event
    (window as any).ga('send', 'pageview', e.detail.pathname);

Here is an example of this demo.

Consider using this library until there will be some official events support delegated by stencil router. I reckon they will implement kind of these very soon.