I am tying to prevent a webpage reload when the user presses enter on the address bar. Using JQuerys e.preventDefault() method in Google Chrome does not work in the beforeunload method. In general, is this possible to achieve this goal with JQuery or JS or do I need another technique?. If it is possible can someone help me to fix this?
Asked
Active
Viewed 350 times
1
-
you can find answer here `https://stackoverflow.com/questions/3527041/prevent-any-form-of-page-refresh-using-jquery-javascript` – Madhu Magar Sep 15 '20 at 07:21
-
I have tried this $(window).on('beforeunload', function(event) { ... }); but it doesn"t work. Do I need to return something because I don"t need this in my code. I have tried this here also but it doesn"t work: https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event. – mike Sep 15 '20 at 07:23
2 Answers
2
You simply can't to do it. It is not possible to deal with address bar itself from JavaScript. You can only add the confirmation dialog.

Slava Melnik
- 103
- 7
-
And what technique (framework, library etc.) should I apply to get this working? – mike Sep 15 '20 at 07:29
-
I have tried to add a confirmation dialog in the beforeunload method but the dialog gets not displayed. Only this method gets printed in the devtools of the browser: Blocked confirm('LEAVING') during beforeunload. – mike Sep 15 '20 at 08:38
0
Short answer: You can not.
Think it this way, When the user hits enter in address bar
, the user is entering an URL and trying to reach that, And it is handled by the browser only. You can(and should) not block the user from leaving the page. Utmost, you can notify the user before leaving the existing page.
If you are doing this For performance optimization, consider caching the static files.

Sheelpriy
- 1,675
- 17
- 28