Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 28 additions & 10 deletions packages/react-native-web/src/exports/BackHandler/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,35 @@
*
* @flow
*/
const listeners: Array<() => boolean | null | undefined> = []
const addEventListener = (event: 'hardwareBackPress', listener: () => boolean | null | undefined) => {
listeners.unshift(listener);
};

const removeEventListener = (event: 'hardwareBackPress', listener: () => boolean | null | undefined) => {
listeners.splice(listeners.indexOf(listener), 1);
};

function emptyFunction() {}
// Hack for Chrome. See this issue: https://stackoverflow.com/questions/64001278/history-pushstate-on-chrome-is-being-ignored?noredirect=1#comment113174647_64001278
const onFirstPress = () => {
history.pushState(null, '', window.location.href)
window.removeEventListener('focusin', onFirstPress)
};
window.addEventListener('focusin', onFirstPress);

// Detect pressing back key on web browsers
window.addEventListener('popstate', (e) => {
const handled = listeners.find(l => l());
if (handled) e.preventDefault();
});

const BackHandler = {
exitApp: emptyFunction,
addEventListener() {
return {
remove: emptyFunction
};
},
removeEventListener: emptyFunction
const exitApp = () => {
listeners.length = 0;
history.previous();
};

export default BackHandler;
export default {
addEventListener,
exitApp,
removeEventListener
};