I have a question for JavaScript.

Asked 1 years ago, Updated 1 years ago, 272 views

A.jsp B.jsp C.jsp

There's a .

Pressing the button on A.jsp moves you to B.jsp.

In B.jsp, go to C.jsp when you press a browser refresh or f5 keyboard

You are about to write a script.

Is it possible?

I've used onbeforeunload so far.

if (document.readyState=="loading") { 
  location.href='http://naver.com'; 
}

I've tried it.

It's just being moved right away.

It should be moved when the firm refresh and f5 key are pressed.

javascript

2023-01-26 19:39

1 Answers

There must be a way to hang a key-down event throughout the document to stop the basic operation and move it to the desired page.

document.addEventListener('keydown', e => {
  if (e.key === 'F5') {
    e.preventDefault();
    location.href = 'https://example.com';
  }
});

However, it is not recommended to prevent this type of functioning of the original browser because it hurts the user experience.

For example, if you open the developer tool, there is a blog that is designed to unconditionally send it to another specific page, and even if you open a favorite window (firefox only), it recognizes it as a developer tool and forces the page to change. It was very unpleasant.

Additional information.

With the code I wrote above, I can prevent the F5 key and CTRL + R by making a slight change, but I can't prevent clicking the refresh button on the browser with a mouse click.

// This code does not work as intended
window.addEventListener('unload', e => {
  e.preventDefault();
  location.href = 'https://example.com';
});

You can take advantage of the unload event, but the unload event handler blocks scripts in your browser that prevent forced page movement or refresh. 그리고 unload는 Problems such as incompatibility with back/forward cache.

// This code displays a confirm window before leaving the page.
window.addEventListener('beforeunload', e => {
  e.preventDefault();
  e.returnValue = '';
});

Beforeunload is similar to an unload event. Forced page movement is not possible, but by using the code written above:

Do you want to reload the site? Changes may not be saved.

It is possible to display a confirmation window for these messages. And, as described by MDN, there is a similar issue with unload.

✅ Control using key input events is possible.
❌ Unload, beforeunload event control is not possible.

Therefore, the desired functionality cannot be fully implemented.


2023-01-26 22:09

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.