3
I have, for example, a function myFunction()
to be called in the element <body>
when the event onbeforeunload
occur:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>example</title>
</head>
<body onbeforeunload="return myFunction()">
<a href="https://www.w3schools.com">Click here to go to w3schools.com</a>
<script>
function myFunction() {
return "Write something clever here...";
}
</script>
</body>
</html>
But for the function myFunction
be called I need to give a return
in the event attribute, because that way doesn’t work:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>example</title>
</head>
<body onbeforeunload="myFunction()">
<a href="https://www.w3schools.com">Click here to go to w3schools.com</a>
<script>
function myFunction() {
return "Write something clever here...";
}
</script>
</body>
</html>
Why do you say it doesn’t work?
– Costamilam
In the first example the beforeunload event runs already in the second no
– user178466
It does not call the function in the second example, only if I return the function.
– user178466
Declare the event
onbeforeunload
in the window object<h1 id='titulo'>Teste</h1><script>window.addEventListener('beforeunload', function (e) {document.getElementById('titulo').innerText= 'beforeunload';});</script>
– Augusto Vasques
Hello Welcome to Sopt, what I’m imagining is that you are wanting to present the data of your string somewhere, the return will return, but will not show anything on your screen because you did not give rise to it, you would have to present it somehow, like:
<script>var dado = myFunction(); alert(dado);</script>
– Ivan Ferrer
or:
<script>var retornado = myFunction(); document.body.innerText = retornado;</script>
– Ivan Ferrer
@Ivanferrer This beforeunload event is special because of the "tradition" and the sensitive context it automatically displays a confirm with the text returned by Event Handler.
– bfavaretto
Yes, beforeunload is an auto-envocation function that captures a return before any event is loaded. [+]
– Ivan Ferrer
[+] it captures what you process within the function and requires it to have a return, so it makes no sense not to return it, but the function that is called can execute a script, or a subFuncao, does not necessarily need anything other than a
return ...
external.– Ivan Ferrer
When hitting a page the following example will be called:
var change = true; window.onbeforeunload = function() {
 if (change) {
 return 'Há modificações para serem salvas. Are you sure you want to leave?';
 }
}– Ivan Ferrer