If you would take a look to Stencil Router documentation, you wouldn't find any info about open nor close page events, so how we would listen to them? I made a simple library for this scope.
Let's say we have an application compiled by Stencil which contains more than one page. Now, we would like to add Google Analytics on our pages. Let's see how we can implement this purpose.
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 installing, we have to add <ip-stencil-route-listener />
component inside of routeRender function of <stencil-riuter />
. Take a look to red lines:
Nothing much! Now each time when you'll 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:
@Listen('pageEnter')
onPageEnter(e: CustomEvent<LocationSegments>) {
// This is a Goolge Analytics event
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 events very soon.
Top comments (3)
Thanks for your component. I used it and it is working fine when I run
npm start
but when I build my project by runningnpm run build
and then runserve www/
the events are not working. Do you have any ideas why ?...or maybe the Stencil team won't be adding events:
github.com/ionic-team/stencil-rout...
Yes, unfortunately they won't, maybe it's time to improve this little plugin.