What is the replacement for performance.navigation.type in angular?
Asked Answered
C

3

12

I have this code in order to know if the page is reload by the user, unfortunately is deprecated. I want to know if angular has this approach.

if (performance.navigation.type === 1) {
   console.log('is refreshed')
}

if (performance.navigation.type === 0) {
   console.log('the user is arrived')
}  
Crosscurrent answered 1/11, 2019 at 0:56 Comment(0)
J
9

Not specific to Angular, but this API has been replaced by the PerformanceNavigationTiming one, which also has a type property, but which returns a string instead of a numerical code.

However I just noticed that Chrome won't expose this for iframes, which will always output "navigate".

The following snippet won't work in Chrome, please try this plnkr instead, in external view.

const entries = performance.getEntriesByType("navigation");

console.log( entries.map( nav => nav.type ) );

rel.onclick = e => location.reload();
<button type="button" id="rel">reload</button>
<a href="404">go to 404 (come back with your browser's back button)</a>
Jannelle answered 1/11, 2019 at 1:38 Comment(1)
Nice one, though mind that "This is an experimental technology, expect behavior to change in the future."Contrecoup
G
17

performance.navigation was deprecated. To get navigation type you can use getEntriesByType

Example

console.log(performance.getEntriesByType("navigation")[0].type)

The type value can be

enum NavigationType {
    "navigate",
    "reload",
    "back_forward",
    "prerender"
};

See more: https://w3c.github.io/navigation-timing/#sec-performance-navigation-types

Goode answered 10/2, 2021 at 2:41 Comment(0)
J
9

Not specific to Angular, but this API has been replaced by the PerformanceNavigationTiming one, which also has a type property, but which returns a string instead of a numerical code.

However I just noticed that Chrome won't expose this for iframes, which will always output "navigate".

The following snippet won't work in Chrome, please try this plnkr instead, in external view.

const entries = performance.getEntriesByType("navigation");

console.log( entries.map( nav => nav.type ) );

rel.onclick = e => location.reload();
<button type="button" id="rel">reload</button>
<a href="404">go to 404 (come back with your browser's back button)</a>
Jannelle answered 1/11, 2019 at 1:38 Comment(1)
Nice one, though mind that "This is an experimental technology, expect behavior to change in the future."Contrecoup
T
5

I want to add that running:

performance.getEntriesByType("navigation");

returns an empty array in Safari

Tertias answered 26/5, 2021 at 18:50 Comment(1)
same issue for me in Safari, were you able to find a solution?Lianneliao

© 2022 - 2024 — McMap. All rights reserved.