Dismiss-Then-Navigate: A Browser Notice Helper in Plain JS
Data Structure DesignModel answerLast 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:
- The moment it is called, the user sees a popup containing
message. - 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.locationor calling one of its methods. - If
targetUrlis 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.
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
The key question: does the popup block?
Everything hinges on whether showing the popup pauses your script.
- Native
alert()is synchronous. The script stops on that line and continues only after the user dismisses the dialog (OK, Enter or Escape). Placing the navigation on the next line already gives the required order: show, wait, then go. No callback, timer or event listener is needed. - A DOM-built modal is asynchronous. The function inserts elements and returns immediately. The navigation therefore cannot sit at the end of the function. It must run inside the handler that closes the modal.
In a time-boxed setting, give the alert version first because it is short and fully correct, then present the custom modal as the more flexible option.
The URL check
Navigate only if typeof targetUrl === "string" && targetUrl.length > 0.
This rejects "", null, undefined, numbers, objects and arrays. The message is still shown in those cases, since the rule only suppresses the navigation.
A string of only spaces is technically non-empty, so a literal reading navigates. Trimming first is a defensible stricter variant. Whichever you choose, say so explicitly.
Version 1: native dialog
function showPopupAndRedirect(message, targetUrl) {
// Execution halts here until the user closes the dialog.
window.alert(message);
if (typeof targetUrl === "string" && targetUrl.length > 0) {
window.location.assign(targetUrl);
}
}
- The dialog is the first statement, so it appears immediately.
- Code after
alertcan only run once the dialog is gone. location.assign(url)is standard navigation and behaves like settinglocation.href.
Version 2: custom modal
function showPopupAndRedirect(message, targetUrl) {
const canNavigate = typeof targetUrl === "string" && targetUrl.length > 0;
const backdrop = document.createElement("div");
backdrop.style.cssText =
"position:fixed;inset:0;background:rgba(0,0,0,.5);display:flex;" +
"align-items:center;justify-content:center;z-index:2147483647;";
const panel = document.createElement("div");
panel.setAttribute("role", "dialog");
panel.setAttribute("aria-modal", "true");
panel.style.cssText =
"background:#fff;padding:20px 24px;border-radius:8px;max-width:400px;" +
"font-family:sans-serif;";
const body = document.createElement("p");
body.textContent = String(message); // plain text, never parsed as markup
const okBtn = document.createElement("button");
okBtn.type = "button";
okBtn.textContent = "OK";
let finished = false;
function finish() {
if (finished) return; // makes closing idempotent
finished = true;
document.removeEventListener("keydown", onKeyDown);
backdrop.remove();
if (canNavigate) window.location.assign(targetUrl);
}
function onKeyDown(e) {
if (e.key === "Escape" || e.key === "Enter") finish();
}
okBtn.addEventListener("click", finish);
document.addEventListener("keydown", onKeyDown);
panel.append(body, okBtn);
backdrop.appendChild(panel);
document.body.appendChild(backdrop);
okBtn.focus();
}
Points worth calling out:
- Event-driven control flow.
finishis the single exit from the modal, so it owns the navigation. - Run-once guard. The
finishedflag stops a click followed by a keypress from navigating twice. - Cleanup. The key listener is removed and the backdrop is detached, so nothing lingers, which matters in single-page apps.
- Safe text.
textContenttreats the message as literal text, which avoids injection throughinnerHTML. - Accessibility. The panel has
role="dialog"andaria-modal, focus moves to the button, and the keyboard can close it. The built-indialogelement withshowModal()is a modern alternative that also traps focus, and you would navigate from itscloseevent.
assign versus replace
location.assign(url)adds a history entry. Back returns to the current page. It is the neutral default.location.replace(url)swaps out the current entry. It fits pages that exist only to move the user along, because Back would otherwise land on a page that shows the popup and redirects again, trapping the user in a loop.
Either meets the requirement. Mentioning the difference shows you understand session history.
Complexity
Time and space are O(1) for the function itself. The real elapsed time depends on how long the user takes to dismiss the popup.
Edge cases
| Situation | Outcome |
|---|---|
targetUrl is "", null, undefined, 42 or {} | Popup appears, no navigation |
| Whitespace-only URL | Navigates under the literal rule. Trim first for a stricter variant |
message is not a string | alert and String() coerce it, so undefined shows as the word "undefined". You may default to an empty string |
User blocked further dialogs, or sandboxed iframe lacking allow-modals | alert returns at once without displaying anything, so navigation still occurs |
Relative address such as "/login" | The browser resolves it against the current page |
javascript: address from untrusted input | Would execute script. Parse with new URL(targetUrl, location.href) and allow only http: and https: if the value is not trusted |
Common mistakes
- Using
setTimeoutto "wait" for the dialog. It is unnecessary withalertand unreliable with a custom modal. - Calling
location.assignstraight after building the custom modal, which navigates before the user sees anything. - Skipping the popup when the URL is invalid. Only the navigation should be skipped.
- Setting the message through
innerHTML. - Letting the close handler fire twice.
Likely follow-ups
- Swap the hand-built modal for the native
dialogelement. - Return a Promise that resolves when the popup closes, so callers can
awaitit and the two versions share one interface. - Add a Cancel button that closes the popup without navigating.
- Navigate automatically after a visible countdown.