js实现页面的跳转页面
使用 window.location.href
通过修改 window.location.href 属性实现页面跳转,浏览器会加载新的 URL 并跳转到目标页面。
window.location.href = "https://example.com";
使用 window.location.replace
window.location.replace 方法会替换当前页面在历史记录中的条目,用户无法通过返回按钮回到原页面。
window.location.replace("https://example.com");
使用 window.location.assign
window.location.assign 方法加载新页面,保留历史记录,用户可以通过返回按钮回到原页面。
window.location.assign("https://example.com");
使用超链接模拟点击
通过编程方式模拟用户点击超链接的行为,适用于需要触发导航事件的情况。
const link = document.createElement("a");
link.href = "https://example.com";
link.click();
使用 meta 标签自动跳转
在 HTML 中插入 meta 标签实现自动跳转,通常用于页面重定向。
<meta http-equiv="refresh" content="0; url=https://example.com">
使用表单提交跳转
通过动态创建表单并提交,适用于需要 POST 请求的跳转场景。
const form = document.createElement("form");
form.method = "POST";
form.action = "https://example.com";
document.body.appendChild(form);
form.submit();
使用 History API
通过 History API 修改当前 URL 但不刷新页面,适用于单页应用(SPA)的路由跳转。
window.history.pushState({}, "", "https://example.com");
使用 iframe 跳转
在 iframe 中加载目标页面,适用于需要嵌入其他页面的场景。
const iframe = document.createElement("iframe");
iframe.src = "https://example.com";
document.body.appendChild(iframe);
使用导航事件触发
通过触发 popstate 或 hashchange 事件实现基于哈希的路由跳转。
window.location.hash = "newHash";
window.dispatchEvent(new HashChangeEvent("hashchange"));
使用 Web Workers 跳转
在 Web Worker 中执行跳转逻辑,适用于后台任务触发的页面跳转。
const worker = new Worker("worker.js");
worker.postMessage({ command: "redirect", url: "https://example.com" });






