KatInterview

Dismiss-Then-Navigate: A Browser Notice Helper in Plain JS

Data Structure DesignModel answer
EasyModel answerData Structure Designjavascriptdombrowser-apis

Last updated

Write a vanilla JavaScript function that shows a message to the user and moves the page to a given address once the message is closed, skipping the move when the address is not a non-empty string.

You are building a small piece of front-end code for a modern browser with JavaScript enabled. Use plain JavaScript only. No frameworks or third-party packages.

Task

Write a function showPopupAndRedirect(message, targetUrl) with this behavior:

  1. The moment it is called, the user sees a popup containing message.
  2. After the user closes the popup, the browser navigates the current page to targetUrl.

Rules

  • The popup must come from built-in browser capabilities. A native dialog (alert, confirm) is fine, and so is a modal you assemble yourself from DOM elements.
  • Navigation must use a standard browser mechanism, such as assigning to window.location or calling one of its methods.
  • If targetUrl is not a non-empty string, the function must not navigate.
  • Beyond that single check, no error handling is needed.

What to deliver

Describe your approach and then give the code. Be prepared to explain:

  • how the order of events differs between a native dialog and a custom DOM modal,
  • which values count as "not a non-empty string" and whether the popup still appears for them,
  • the practical differences between the available navigation methods.

Hints

Hint 1

Ask yourself whether the line after a native `alert(...)` call can run while the dialog is still open. What does that tell you about where the navigation statement can go?

Hint 2

A modal built from DOM elements does not pause the script. Where does the navigation have to be triggered, and how would you make sure it only happens once even if the user clicks the button and presses a key?

Hint 3

Define the validity test precisely (type and length). The popup should still be shown when the address is invalid, because only the navigation is suppressed. Compare `location.assign` and `location.replace` in terms of the Back button.