WICG / navigation-api

The new navigation API provides a new interface for navigations and session history, with a focus on single-page application navigations.
https://html.spec.whatwg.org/multipage/nav-history-apis.html#navigation-api
484 stars 30 forks source link

navigation.intercept() #246

Closed fabiancook closed 1 year ago

fabiancook commented 1 year ago

This is a bit of detour from addEventListener, but it seems very possible to add a "top level" intercept as a shortcut

Without committing to adding handlers, it could be useful for changing the way navigation works without adding an event listener

// Default intercepts every navigate event 
navigation.intercept();
// Provide default options, and change them
navigation.intercept({ commit: "manual" });
navigation.intercept({ scroll: "after-transition" }); // would merge with commit above

Once you do have this function though, having it also accept a handler seems also reasonable, however I think this would be different from any other web api

// Provides navigation event to handler as if it was `addEventListener("navigate", event => event.intercept(() => {}));
navigation.intercept(event => {});
navigation.intercept({
  handler(event) {

  }
})
// commit still available if we are still passing the event
navigation.intercept(event => event.commit());

How nice it would be to have intercept across a few different web apis...

fetch.intercept({
  handler(event) {
     if (event.request.url.endsWith("/test")) {
        event.respondWith(new Response("Test!"));
     }
  }
})
domenic commented 1 year ago

It feels like this saves a bit of typing, at the cost of obscuring the mechanism by which this is implemented and works. As such, I don't think we want to go in this direction with the API.

fabiancook commented 1 year ago

Super agree. And it can be easily implemented in userland without much overhead at all...

https://github.com/virtualstate/navigation/blob/17132f9caabf98ee76fad459841e9c649346921b/src/tests/await/index.ts#L40-L46