Repository navigation
Conversation
We can now use BackHandler to listen to the "previous" button on web.
|
I don't understand what this is trying to achieve |
|
The idea is to handle the "previous" button of the browser the same way as the "back" button on devices |
|
Can you be more specific? How does this achieve that? |
|
The idea is to let our app take 2 spaces in the history. Using Each time we move from page 2 to page 1, we can call a list of listeners and decide if we should move back to page 2 in order to listen to further press on From there we should probably define what we expect from a web implementation of BackHandler. In my own use case, I wanted this:
In the implementation I proposed here, it is a bit different:
|
|
Maybe this is something @EvanBacon can provide feedback about. |
|
This could be interesting to fix e.g. the route going back while there is a Modal opened. When the user presses the native back button it would be expected that the modal closes first instead of the route going back. Note that this behaviour would also be the case on desktop devices with the back button. This line is a little bit confusing, this is always the first item, correct? It also always empty a.t.m. since BackHandler. addEventListener is never called. |
|
We should also think about possibly interference of other libraries/code which use history.pushState. + popstate is called on page load if I remember correctly. But I think this would be a really great addition on UX on the web which a lot of (web) libraries have not fixed yet. |
|
Right now, I'm using this system to close modals : I add the close function to the listeners using BackHandler. addEventListener The same way as for RN, this function is supposed to be called in the user application. I'm not sure if I correctly understood and answered your question.... |
|
You're 100% right, I was just too focused on the code that I forgot about the external api which is used and returning booleans! 👍 |
|
In our app, we chose to not use the browser history, because in my opinion, this is a feature that makes sense for a website, but not so much for an application, and moreover, passing data through the url tends to break the normal react data flow. So, for projects that followed that same line, it would be a great addition. But for projects that still make use of history, we first need to decide exactly what the expected behavior of BackHandler should be. Or maybe we should just advice them to not use it for their case. |
|
I think a lot of webapps use the url navigation, I also think this is very important for apps running in a browser for the UX of the user since they are used to the back button in their browser. But I think it could be possible to make both cases working. |
|
I'm not too much afraid of the technical challenge to make it work with history. I'm more wondering if it is possible to define a universal expected behavior for this feature in such a case and if it still makes sense. I don't understand the part of your remark about the back button. Of course, the user can use the back button of their browser. It's just that instead of relying on urls we handle the state changes programmatically. I find this better because we can do it the react way. For instance, pressing the back button 3 times might close a modal, then unset a prop that will makes him navigate to a previous component, and then ask them if they want to leave the app for instance. |
|
I think it depends on the app but I like if an app support ctrl+click with url etc. On-topic: I would really like this feature! |
|
Line 26, if we change history.pushState with history.forward(), the behavior might start looking more like what we could expect, and it should play nicely with an app that uses history. It would just a an extra entry at the very beginning of the stack. Does anyone has a react native app using history that we could use for testing? |
|
Well, if someone comes with a project where this could be used, just tag me, we will see if we can make this work. |
|
@Sharcoux I'm working on a codesandbox with react-router-dom. I'll use a custom modal where we can test the backhandler code ;) |
|
This is hard, the pushState function works very differently from what I would have imagined |
|
Here is the sandbox, but it won't work when you register multiple back handlers, we will need to connect the popState event to the right listener but the event don't has the right content in my case + it can interfere with other things. |
|
I think we need to wait for a better api for navigation on the web, I think it will be too fragile The Chrome team has a proposal for this which looks like it could fix what we are trying to fix |
|
You can see in my example that too much states are pushed when multiple Backhandlers are registered (we need to remove the pushedState when the .remove() is called but this is not possible as far as I know. This results in the back button not working for a few clicks after opening multiple modals and closing them |
|
Here is a GIF showing the problem, and here is the codesandbox: https://codesandbox.io/s/winter-sun-euxm7?file=/src/BackHandler.js |
|
Ok, I don't know what could be the best way to work on this together, but here are my thoughts:
|
We can't go forward if there's no state?
history.states() can't be used unfortunately since this is a proposal and not implemented in browsers yet. That proposal would make this feature a lot easier.
We need to push to the url so we can hook onto going back events, ideally we could maybe register this just once per page instead of every listener.
We can't prevent the browser from going back, so we need to work the other way around |
|
I changed some stuff, and this seems to be more or less what you wanted to achieve, but I might be wrong. I'm just surprised about the history.forward(). If we are pressing back, this means that we are adding something in the stack isn't it? Maybe we need to delay a bit the call using setImmediate to wait for the history to be updated? This might be needed if the popstate listeners are called before the popped state is being added to the forward list. |
|
Your solution works great!! One thing: And we need also need to change the window.history.previous to window.history.back |
|
The addState should really be added at import level. You need it only once and only if the BackHandler is being used. |
|
I've removed some things which are not needed anymore + added multiple backHandler imports to test that out I found 1 problem with the current implementation and that is when you want to go back and show a confirm alert (on the 'Prevent going back' going back page) it does not respect the history.goBack() function https://codesandbox.io/s/thirsty-worker-se765?file=/src/BackHandler.js |
|
I tested it out on an Android phone. It does not work the way it should. |
|
Why not use a onKeyDown listener in the other places? |
|
So that could be cool if we can handle it just by backhandler for native and web both. |
|
Wait a minute guys, I'm not sure to follow. Are you suggesting that BackHandler should react to the escape key? If so, I totally disagree. The role of BackHandler is just to provide the ability to react to the button "back" which would not be possible otherwise. Reacting to "Escape" is totally possible by various other ways and we cannot be sure that the expected behavior of Escape key would be the same as the Back key. But maybe I misunderstand what you mean when you are talking about "escape" |
I checked. Indeed there is an issue when using react-navigation. For some reason, despite calling e.preventDefault() on the popstate event, the state is still being removed from the history. I also notice that the initial pushState is also being ignored in some cases... I wonder if react-navigation is not itself doing some nasty treatment to the history. |
|
If you're looking for my feedback, I don't think It is triggered on both back and forward buttons, long pressing one of those buttons and selecting a history entry, calling It's also not possible to prevent the event which makes it impossible to implement the
It definitely makes sense for apps as well. Native apps implement deep linking which isn't that different.
Nasty treatment is a strong word, React Navigation manages history on web unless you disable it. If you intefere with history as well, of course it won't be able to properly keep track of changes and things will break. So you either let React Navigation manage history or pass
You can't prevent The use case for "preventing going back" needs to be implemented in React Navigation. Since React Navigation keeps track of history already, it has a better idea of how to handle preventing a histiry change.
React Navigation doesn't use IIRC the |
|
I agree with @satya164, I like the way react-navigation works with url's by default! My opinion: I think the browser api in its current state can't work well enough with the possible use-cases of the BackHandler Maybe this proposal: https://github.com/slightlyoff/history_api could fix some things but I don't know it will ever be implemented. |
|
Thanks a lot @satya164 , This helped me understand better our options. And indeed, react-navigation is not doing anything nasty, I just didn't know that popState could not be prevented with preventDefault. It just happened to look as if it was working in my use case while it's not. I see 2 options to solve the issue and keep it transparent for react-navigation or any other use of history : 1) Monkey patching the history.You can see the updated sandbox here (warning for some reason it doesn't work if you open the sandbox in a separated tab, but it works in the embed window and it will work in a real app) This is cool because we can make sure that we target only the back button. 2) Using
|
|
You can't override browser back button by monkeypatching What you're trying to do is not possible with the current browser APIs. |
|
Indeed. The back button is not calling Ok, so here is my last proposal taking all this into account. It's basically mixing both approach into something that will work as intended I think. But, this time, it will definitely "do nasty things to the history". The forward button will always be disabled so that we can reliably use It might be debatable if these constraints are acceptable or not for something that would reach the code base, but I think that React-Native-Web is aiming at creating cross-platform apps and with this in mind, even with its limitation, this BackHandler brings a most needed feature that is hard to achieve otherwise. I'd like to hear your own opinion about it. |
You should use
Please don't, users have certain expectations from things running in the browser and have certain workflows. Just because you have a web app, it doesn't mean users will have different expectations. If you don't want to integrate your app with browser history, then that's fine (even though not ideal), but messing with back/forward buttons, and especially from framework code is a big nope. Not to mention, users can still right click the back button and go back to any point in browser history and there's nothing you can do to prevent it. If you want to be able to prompt user from leaving the page, then use the API that browsers provide you to do that.
I don't think this sort of code belongs in React Native Web. It shouldn't mess with browser history. It makes more sense for navigation/routing libraries such as React Navigation to manage browser history. And routing libraries won't be able to have proper browser history integration if something else is messing with browser history. React Navigation already has browser history integration and API for preventing going back from a screen. That API has some bugs, which makes it not work in nested navigators, however, it's a bug in the library and fixable. And it doesn't need doing unexpected things to browser history. |
|
|
I totally understand your point of view. The thing is that, the same way that BackHandler doesn't belong to history libraries on native, it should not belong to react-navigation on browser. Reacting to the user input through the different buttons at their disposal should not be exclusive to some libraries. Especially because from my point of view, URLs management and React are not getting well along and so we should still be able to produce app without depending on navigation libraries. On the other hand, I agree that the BackHandler implementation should not destroy the workflow of the history and the integration with the other libs. I might have a new idea. Let me try it out. |
Sure, but there's no API to detect back button in browser. It's not equivalent to the History API. You're not reacting to buttons. What's equavalent is the On all other platforms,
Would it be cool if we didn't need to use third party libs? Yes. But every addition of code has a cost and increases maintenance burden. I'd rather have a good base in core and let third party libs provide good quality integrations than have poorly maintained code in core. Not long ago, a lot of code was extracted to third party libraries from React Native core due to maintenance issues. While it'll be nice to have such full integration built-in, it's not a trivial problem. I have spent weeks to implement it in React Navigation at minimum, and countless other weeks debugging edge cases, and there are still problems with it. There are libraries like React Router which spent years trying to solve this space. History API has a lot of problems, whatever hacks you end up with are going to break in ways you wouldn't have anticipated. I have already tried and I don't recommend it. |
|
You've got me wrong. I'm not saying that using If we disagree on that it is probably because the kind of applications we have in mind are very different and it should be enough to just agree that both should be achievable, and that single page application would greatly profit from a common API for back buttons on mobile and browser. About the current problem, there is actually a way to know if the In this fork where I just commented out all the meaningful code from the BackHandler, so it is just vanilla |
|
@HosseinMD maybe you can help me understand the fact that the back button doesn't work in your sandbox even when I remove the BackHandler part. I must be missing sth. |
|
Closing this PR because there doesn't seem to be a good way forward and the behavior isn't supported by APIs on web. Thanks for the discussion |
|
@HosseinMD @necolas I will provide my last code this weekend. I think that it can be considered as working as expected and respecting the constraints that were raised here. It should be compatible with react-navigation. The only issue is that I don't know react navigation and in the provided demo, it doesn't work as expected even without my code. |
|
@HosseinMD @satya164 this implementation of the BackHandler should work fine with react-navigation. |
|
checked it, but I don't understand what going on. |
|
@HosseinMD well it's a simplified test case. WithUrls is using history to handle navigation and pressing back in the browser will move you one step back. WithoutUrls is using only the BackHandler and state management to navigate in the app. If someone knows how to correctly configurate react navigation to be able to use the history, you can replace the current navigation system. |
|
Let's hope this api will be accepted in all browsers it would probably fix this use case |
|
For those interested, here is my final version that I'm using in my app with success on all browsers: BackHandler.tsimport type { BackHandler, BackPressEventName } from 'react-native'
const listeners = [] as (() => boolean | null | undefined | void)[]
const addEventListener = (
event: BackPressEventName,
listener: () => boolean | null | undefined | void
) => {
listeners.unshift(listener)
return { remove: () => removeEventListener(event, listener) }
}
const removeEventListener = (
_event: 'hardwareBackPress',
listener: () => boolean | null | undefined | void
) => {
listeners.splice(listeners.indexOf(listener), 1)
}
const back = window.history.back
window.history.back = function () {
const handled = listeners.find(l => l())
if (!handled) {
return back.apply(window.history, [])
}
}
window.addEventListener('popstate', () => {
const handled = listeners.find(l => l())
if (!handled) {
back.apply(window.history, [])
}
window.history.pushState(null, '', window.location.href)
})
// Hack for Chrome. See this issue: https://stackoverflow.com/questions/64001278/history-pushstate-on-chrome-is-being-ignored?noredirect=1#comment113174647_64001278
const onFirstPress = () => {
window.history.pushState(null, '', window.location.href)
window.removeEventListener('focusin', onFirstPress)
}
window.addEventListener('focusin', onFirstPress)
const exitApp = () => {
listeners.length = 0
back.apply(window.history, [])
}
export default {
addEventListener,
exitApp,
removeEventListener,
} as BackHandlerYou can also use this helper if you want to import React from 'react'
import BackHandler from './BackHandler'
/** This helper will call onBackPress when we press the hardware back button */
const useBackKey = (onBackPress?: () => void) => {
React.useEffect(() => {
if (!onBackPress) return
const onBack = () => {
onBackPress()
return true
}
BackHandler.addEventListener('hardwareBackPress', onBack)
return () => BackHandler.removeEventListener('hardwareBackPress', onBack)
}, [onBackPress])
}
export default useBackKeyOf course, my use case is not necessarily yours. But if you're struggling, I think it is worth a try. |
|
Thanks @Sharcoux , saved my life. The code above didn't work for me for some reason but the codesandbox you linked did. I feel like this should be the default behavior for react navigation if Platform.OS === 'web', no? Anyway, thanks again, this'll work in the meantime. |
|
@zachdixon can you elaborate on why the last code I provided didn't work? Normally, this implementation is better than the implementation in the codesandbox. |

I got that idea while working on a problem a bit similar in my RN + RNW app.
I don't know if this can be useful to other people.
I let it as a draft as I didn't test this exact version of the code, but I can do it if it has a chance to be accepted.
The idea is to push a fake duplicate of the app url on load, so that when we press "back", we detect that the history has changed, and we can take actions.