virtualstate / navigation

Native JavaScript navigation [web api] implementation
MIT License
77 stars 5 forks source link

Navigation by setting window.location does not trigger navigate event #27

Open aigan opened 5 months ago

aigan commented 5 months ago

Prerequisites

Version (i.e. v2.x.x)

1.0.1-alpha.200

Node.js version (i.e. 18.x, or N/A)

v18.16.0

Operating system

Linux

Operating system version (i.e. 20.04, 11.3, 10, or N/A)

Debian 12.5

Description

Setting window.location will not trigger a navigate event. With the navigation api working on chrome, you can intercept page changes by window.location.

Using the navigation.navigate() method works fine. The README should list all differences. Implement window.location, or make it an option or list it as a limitation.

Steps to Reproduce

See example in https://github.com/aigan/virtualstate-navigation-bugs using the navigation buttons

Expected Behavior

Should work the same as in Chrome with the navigation api.

fabiancook commented 5 months ago

Curious, I would have expected for the history API to update when this happens, but looks like we will need to patch the window & location globals to intercept this specific type of navigation.

Makes sense if it doesn't change history at all before navigating.

fabiancook commented 5 months ago

It is not possible to replace the window.location, nor the global window, making it not possible to polyfill this specific functionality directly it appears.

Safari:

> Object.defineProperty(window, "location", { value: { test: 1 }} )
< TypeError: Attempting to change access mechanism for an unconfigurable property.
> Object.defineProperty(globalThis, "window", { value: { test: 1 }} )
< TypeError: Attempting to change access mechanism for an unconfigurable property.

Chrome:

Object.defineProperty(window, "location", { value: { key: "test" } })
VM496:1 Uncaught TypeError: Cannot redefine property: location
    at Function.defineProperty (<anonymous>)
    at <anonymous>:1:8

The way forward would be to document this restriction, there may be as well though another way to hook onto this functionality though (of navigating with window.location = "string", will need to investigate further.

Potentially a beforeunload would be a viable direction if it does capture the target href somehow.

aigan commented 5 months ago

A list of limitations in the readme would be good.