行js实现
JavaScript 实现方法
使用 window.location.href 进行跳转
通过修改 window.location.href 属性实现页面跳转,这是最常用的方法之一。代码示例如下:
window.location.href = "https://example.com";
使用 window.location.replace 替换当前页面
此方法会替换当前页面在浏览历史中的记录,用户无法通过“后退”按钮返回原页面。
window.location.replace("https://example.com");
使用 window.open 打开新窗口或标签页
通过 window.open 可以在新窗口或标签页中打开目标链接。
window.open("https://example.com", "_blank");
使用 location.assign 方法
与 window.location.href 类似,但语义更明确。
window.location.assign("https://example.com");
通过表单提交实现跳转
动态创建表单并提交,适用于需要传递参数的场景。
const form = document.createElement("form");
form.method = "GET";
form.action = "https://example.com";
document.body.appendChild(form);
form.submit();
使用 meta 标签自动跳转
在 HTML 中插入 meta 标签实现自动跳转,适用于纯前端场景。
const meta = document.createElement("meta");
meta.httpEquiv = "refresh";
meta.content = "0;url=https://example.com";
document.head.appendChild(meta);
通过 history.pushState 修改 URL 而不刷新页面
适用于单页应用(SPA)中的路由跳转。
history.pushState({}, "", "https://example.com");
注意事项

- 跨域限制:部分方法(如
window.open)可能被浏览器拦截。 - 安全性:避免使用未经验证的动态 URL,防止 XSS 攻击。
- 兼容性:确保目标浏览器支持所选方法。






