JavaScript - 页面重定向



什么是页面重定向?

您可能遇到过这样的情况:您点击了一个 URL 要访问页面 X,但实际上您被重定向到了另一个页面 Y。这是由于 **页面重定向** 造成的。这个概念与 JavaScript 页面刷新 不同。

您可能出于各种原因想要将用户从原始页面重定向到其他页面。我们列出了一些原因:-

  • 您不喜欢您的域名,并且要迁移到一个新的域名。在这种情况下,您可能希望将所有访问者重定向到新网站。您可以保留旧域名,但将其指向一个包含页面重定向的单一页面,以便所有旧域名访问者都能访问您的新域名。

  • 您根据浏览器版本或名称,或者可能是根据不同的国家/地区构建了多个页面,那么,与其使用服务器端页面重定向,不如使用客户端页面重定向将您的用户引导到相应的页面。

  • 搜索引擎可能已经索引了您的页面。但在迁移到另一个域名时,您不希望失去来自搜索引擎的访问者。因此,您可以使用客户端页面重定向。但请记住,不要这样做来欺骗搜索引擎,这可能导致您的网站被封禁。

页面重定向是如何工作的?

页面重定向的实现如下所示。

示例 1

使用客户端的 JavaScript 进行页面重定向非常简单。要将您的网站访问者重定向到新页面,您只需在头部部分添加一行代码,如下所示。

<html>
<head>
    <title>Page Redirection Example</title>
</head>
<body>
    <p>Click the following button, you will be redirected to home page.</p>
    <form>
        <input type="button" value="Redirect Me" onclick="Redirect();" />
    </form>
    <script type="text/javascript">
        function Redirect() {
            window.location = "https://tutorialspoint.com";
        }
    </script>
</body>
</html>

示例 2

在将访问者重定向到新页面之前,您可以向他们显示一条适当的消息。这需要一点时间延迟才能加载新页面。以下示例显示了如何实现这一点。这里的 **setTimeout()** 是一个内置的 JavaScript 函数,可用于在给定时间间隔后执行另一个函数。

<html>
<head>
    <title>Page Redirection Example</title>
</head>
<body>
    <p>You will be redirected to main page in 10 sec.</p>
    <script>
        function redirect() {
           window.location = "https://tutorialspoint.com";
        }            
        setTimeout('redirect()', 10000);
    </script>
</body>
</html>

输出

You will be redirected to tutorialspoint.com main page in 10 seconds!

示例 3

以下示例显示了如何根据用户的浏览器将他们重定向到不同的页面。

<html>
<head>     
   <title>Browser Redirect</title>
</head>   
<body>
   <script type = "text/javascript">
      var browsername = navigator.appName;
      if( browsername == "Netscape" ) {
         window.location = "https://tutorialspoint.com/javascript/index.htm";
      } else if ( browsername =="Microsoft Internet Explorer") {
         window.location = "https://tutorialspoint.com/articles/category/Javascript";
      } else {
         window.location = "https://tutorialspoint.com/";
      }
   </script>      
</body>
</html>
广告

© . All rights reserved.