如何使用 JavaScript 重定向网页

要使用 JavaScript 重定向 URL 页面,我们需要设置 window.location 对象。

有几种方法可以更改 window 对象上的 location 属性:

  • window.location.href - 返回当前页面的 URL。
<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
  </head>
  <body>
    <script>
      let url = "https://www.onitroad.com";
      window.location.href = url;
    </script>
  </body>
</html>
  • window.location.hostname - 返回当前页面的 Internet 主机的名称。
<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
  </head>
  <body>
    <button type="button" onclick="redirectFunc()">点击进入页面</button>
    <script>
      function redirectFunc() {
        window.location.href = "https://www.onitroad.com/";
      }
    </script>
  </body>
</html>
  • window.location.replace - 从历史记录中删除当前 URL 并将其替换为一个新 URL,该 URL 禁止使用后退按钮转到上一页。
<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
  </head>
  <body>
    <script>
      function redirectFunc() {
        window.location.replace("https://www.onitroad.com/");
      }
      setTimeout("redirectFunc()", 2000);
    </script>
  </body>
</html>
  • window.location.assign - 保留历史记录,只需单击后退按钮即可返回原始页面。
<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
  </head>
  <body>
    <script>
      function redirectFunc() {
        window.location.assign("https://www.onitroad.com/");
      }
      setTimeout("redirectFunc()", 2000);
    </script>
  </body>
</html>

我们最好使用 window.location.replace 而不是 .href,因为 replace 方法会导航到 URL,而不会向历史记录添加新记录;因此,读者不会迷失在无休止的后退按钮混乱中。

如果我们想让用户点击链接,请使用 .href,如果我们要进行 HTTP 重定向,请使用 .replace。

如果浏览器中禁用了 JavaScript,这将不起作用。

日期:2020-06-02 22:16:24 来源:oir作者:oir