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.open 跳转
window.open 可在新窗口或标签页中打开目标页面,支持自定义窗口参数(如尺寸、工具栏等)。
window.open('https://example.com', '_blank');
使用 location.assign 跳转
location.assign 与 window.location.href 类似,但语义更明确,同样会在历史记录中保留当前页。
location.assign('https://example.com');
使用 meta 标签自动跳转
通过 HTML 的 <meta> 标签实现自动跳转,通常用于静态页面或 SEO 场景。
<meta http-equiv="refresh" content="5; 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.pushState 或 history.replaceState 可修改浏览器地址栏 URL 而不刷新页面,适用于单页应用(SPA)。
history.pushState({}, '', '/new-page');
使用导航事件跳转
通过触发锚标签(<a>)的点击事件实现跳转,模拟用户点击行为。
const link = document.createElement('a');
link.href = 'https://example.com';
link.click();
注意事项
- 安全性:避免使用
javascript:伪协议跳转(如location.href = 'javascript:alert(1)'),可能引发 XSS 风险。 - 兼容性:
history.pushState仅支持现代浏览器,需处理旧版浏览器的回退逻辑。 - 用户体验:跳转前可添加确认对话框或加载提示,避免突兀切换。







