Skip to content

Instantly share code, notes, and snippets.

@barneycarroll
Created June 15, 2024 12:12
Show Gist options
  • Save barneycarroll/e5bd06fa0ae9abeb6a683eb9a95d5250 to your computer and use it in GitHub Desktop.
Save barneycarroll/e5bd06fa0ae9abeb6a683eb9a95d5250 to your computer and use it in GitHub Desktop.
A `beforeonunload` emulator for Mithril
function BeforeUnload(){
const route. = m.route.set
const handler = e => {
if(
e.target.href
&&
e.target != '_blank'
&&
!confirm(message)
){
// Need to prevent (native behaviour) & stop (Mithril bindings)
e.preventDefault()
e.stopPropagation()
}
},
return {
view: () => {},
oncreate: ({attrs: {message = 'Are you sure?'}}) => {
addEventListener('click', handler, true)
m.route.set = function(){
if(confirm(message))
return route.apply(this, arguments)
}
},
onremove: () => {
removeEventListener('click', handler, true)
m.route.set = route
},
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment