Is there a way to capture a page leave (like some websites do) to allow preventing leaving or to perform cleanup?
You can have a look at JavaScript function that does this https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onbeforeunload_dom
It’s not great on iOS though.
It’s also implemented in the HashRouting module - https://github.com/s-cork/HashRouting/blob/master/README.md
Hi sc549, it seems thata event.returnValue is the value when the leave button is clicked. How can I transfer that value to client code?
<script>
window.onbeforeunload = function(event) {
event.returnValue = "Write something clever here..";
};
</script>
maybe do something like…
anvil.call($'.content', 'function_to_handle_unload', somevalue)
the function would be in the open_form
def function_to_handle_unload(self, value):
## do something
But you’d need to play around with this a bit I think…
Thank you, I will try
It seems that window.onbeforeunload has bug, closing the page when it loads doesn’t trigger the function.
Only after pressing F5 or clicking on a link, and click cancel, the function works well with closing the page
<script>
window.onbeforeunload = function(event) {
event.returnValue = "Write something clever here..";
};
</script>```
My further investigation shows that users need to interact with the page (click any where, press a key…) to makes the code works as expected
Below are complete code that insert value into table when users leave page
<div class="leaving"></div>
<script>
window.onbeforeunload = function(event) {
event.returnValue = "Write something clever here..";
add_status();
};
function add_status(){
var firstArgument = $('.leaving');
anvil.call(firstArgument, "add_status_client", "leaving").then(function (r) {
console.log("The function returned:", r);
});
e.preventDefault();}
</script>
def add_status_client(self, status):
anvil.server.call('add_status', status)
@anvil.server.callable
def add_status(status):
row = app_tables.test.add_row(status=status)