首页 文章

如何重定向到其他网页?

提问于
浏览
7735

如何使用jQuery或纯JavaScript将用户从一个页面重定向到另一个页面?

30 回答

  • 203

    这适用于jQuery:

    $(window).attr("location", "http://google.fr");
    
  • 270

    先写好吧 . 您希望在应用程序中导航,从您的应用程序中为另一个链接导航 . 这是代码:

    window.location.href = "http://www.google.com";
    

    如果你想在你的应用程序中导航页面,那么我也有代码,如果你想 .

  • 63

    基本上 jQuery 只是一个 JavaScript framework 并且在这种情况下做一些像 redirection 这样的事情,你可以使用纯JavaScript,所以在这种情况下你有3个选项使用vanilla JavaScript:

    1)使用location replace ,这将替换页面的当前历史记录,这意味着无法使用 back 按钮返回原始页面 .

    window.location.replace("http://stackoverflow.com");
    

    2)使用location assign ,这将为您保留历史记录,使用后退按钮,您可以返回原始页面:

    window.location.assign("http://stackoverflow.com");
    

    3)我建议使用以前的方法之一,但这可能是使用纯JavaScript的第三个选项:

    window.location.href="http://stackoverflow.com";
    

    您也可以在jQuery中编写一个函数来处理它,但不推荐使用它,因为它只有一行纯JavaScript函数,如果您已经在窗口范围内,也可以使用所有上述函数而不使用窗口,例如 window.location.replace("http://stackoverflow.com"); 可能是 location.replace("http://stackoverflow.com");

    我还会在下面的图片中显示所有内容:

  • 57

    我只需要用另一个更新的jQuery方法来更新这种荒谬:

    var url = 'http://www.fiftywaystoleaveyourlocation.com';
    $(location).prop('href', url);
    
  • 82

    在您的点击功能上,只需添加:

    window.location.href = "The URL where you want to redirect";
    $('#id').click(function(){
        window.location.href = "http://www.google.com";
    });
    
  • 1529

    您需要在代码中添加以下行:

    $(location).attr("href","http://stackoverflow.com");
    

    如果您没有jQuery,请使用以下命令运行JavaScript:

    window.location.replace("http://stackoverflow.com");
    window.location.href("http://stackoverflow.com");
    
  • 287

    Before I start, jQuery is a JavaScript library used for DOM manipulation. So you should not be using jQuery for a page redirect.

    来自Jquery.com的报价:

    虽然jQuery可能在旧浏览器版本中没有出现重大问题,但我们并不主动测试它们中的jQuery,并且通常不会修复可能出现在它们中的错误 .

    它在这里找到:https://jquery.com/browser-support/

    因此,jQuery并不是一种能够实现向后兼容的最终解决方案 .

    以下使用原始JavaScript的解决方案适用于所有浏览器,并且已经标准很长时间,因此您不需要任何库来支持跨浏览器 .

    此页面将在3000毫秒后重定向到 Google

    <!DOCTYPE html>
    <html>
        <head>
            <title>example</title>
        </head>
        <body>
            <p>You will be redirected to google shortly.</p>
            <script>
                setTimeout(function(){
                    window.location.href="http://www.google.com"; // The URL that will be redirected too.
                }, 3000); // The bigger the number the longer the delay.
            </script>
        </body>
    </html>
    

    不同的选项如下:

    window.location.href="url"; // Simulates normal navigation to a new page
    window.location.replace("url"); // Removes current URL from history and replaces it with a new URL
    window.location.assign("url"); // Adds new URL to the history stack and redirects to the new URL
    
    window.history.back(); // Simulates a back button click
    window.history.go(-1); // Simulates a back button click
    window.history.back(-1); // Simulates a back button click
    window.navigate("page.html"); // Same as window.location="url"
    

    使用替换时,后退按钮不会返回到重定向页面,就好像它从未在历史记录中一样 . 如果您希望用户能够返回重定向页面,请使用 window.location.hrefwindow.location.assign . 如果您确实使用了允许用户返回重定向页面的选项,请记住,当您进入重定向页面时,它会重定向您 . 因此,在为重定向选择选项时要考虑到这一点 . 在页面仅在用户完成操作时重定向的情况下,然后在后退按钮历史中具有页面将是可以的 . 但是,如果页面自动重定向,那么您应该使用替换,以便用户可以使用后退按钮而不会强制返回到重定向发送的页面 .

    您还可以使用元数据来运行页面重定向,如下所示 .

    META Refresh

    <meta http-equiv="refresh" content="0;url=http://evil.com/" />
    

    META Location

    <meta http-equiv="location" content="URL=http://evil.com" />
    

    BASE Hijacking

    <base href="http://evil.com/" />
    

    可以在此页面上找到更多将您的毫无疑问的客户端重定向到他们可能不希望访问的页面的方法(其中一个不依赖于jQuery):

    https://code.google.com/p/html5security/wiki/RedirectionMethods

    我还想指出,人们不喜欢被随机重定向 . 仅在绝对需要时重定向人员 . 如果您开始随机重定向人员,他们将永远不会再次访问您的网站 .

    下一部分是假设的:

    您也可能被报告为恶意网站 . 如果发生这种情况,那么当用户点击指向您网站的链接时,用户浏览器可能会警告他们您的网站是恶意的 . 如果人们报告您网站上的不良体验,搜索引擎可能会开始降低您的评分 .

    请查看有关重定向的Google网站站长指南:https://support.google.com/webmasters/answer/2721217?hl=en&ref_topic=6001971

    这是一个有趣的小页面,可以让你离开页面 .

    <!DOCTYPE html>
    <html>
        <head>
            <title>Go Away</title>
        </head>
        <body>
            <h1>Go Away</h1>
            <script>
                setTimeout(function(){
                    window.history.back();
                }, 3000);
            </script>
        </body>
    </html>
    

    如果您将两个页面示例组合在一起,您将拥有一个婴儿循环重新路由,这将保证您的用户永远不会再想要再次使用您的网站 .

  • 72

    试试这个:

    location.assign("http://www.google.com");
    

    Code snippet of example .

  • 177

    这是一个延时重定向 . 您可以将延迟时间设置为您想要的任何时间:

    <!doctype html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <title>Your Document Title</title>
        <script type="text/javascript">
            function delayer(delay) {
                onLoad = setTimeout('window.location.href = "http://www.google.com/"', delay);
            }
        </script>
    </head>
    
    <body>
        <script>
            delayer(8000)
        </script>
        <div>You will be redirected in 8 seconds!</div>
    </body>
    
    </html>
    
  • 35

    # HTML Page Redirect Using jQuery/JavaScript

    试试这个示例代码:

    function YourJavaScriptFunction()
    {
        var i = $('#login').val();
        if (i == 'login')
            window.location = "login.php";
        else
            window.location = "Logout.php";
    }
    

    如果要将完整的URL指定为 window.location = "www.google.co.in"; .

  • 41

    不需要jQuery . 你可以这样做:

    window.open("URL","_self","","")
    

    就这么简单!

    启动HTTP请求的最佳方法是 document.loacation.href.replace('URL') .

  • 149

    但如果有人想重定向回主页,那么他可能会使用以下代码段 .

    window.location = window.location.host
    

    如果您有三个不同的环境,如开发,登台和 生产环境 ,将会很有帮助 .

    您只需将这些单词放在Chrome控制台或Firebug的控制台中即可浏览此窗口或window.location对象 .

  • 161

    在JavaScript和jQuery中我们可以使用以下代码将一个页面重定向到另一个页面:

    window.location.href="http://google.com";
    window.location.replace("page1.html");
    
  • 229

    有三种主要方法可以做到这一点,

    window.location.href='blaah.com';
    window.location.assign('blaah.com');
    

    和...

    window.location.replace('blaah.com');
    

    对于传统的重定向,最后一个是最好的,因为它不会保存您在搜索历史记录中重定向之前所访问的页面 . 但是,如果您只想使用JavaScript打开选项卡,则可以使用上述任何选项卡 . 1

    编辑: window 前缀是可选的 .

  • 548

    应该只能使用 window.location 进行设置 .

    Example:

    window.location = "https://stackoverflow.com/";
    

    这是关于这个主题的过去的帖子:

    如何重定向到其他网页?

  • 365

    你可以在没有jQuery的情况下做到:

    window.location = "http://yourdomain.com";
    

    如果你只想要jQuery那么你可以这样做:

    $jq(window).attr("location","http://yourdomain.com");
    
  • 153

    您可以像这样在jQuery中重定向:

    $(location).attr('href', 'http://yourPage.com/');
    
  • 134
    var url = 'asdf.html';
    window.location.href = url;
    
  • 133

    JavaScript为您提供了许多方法来检索和更改浏览器地址栏中显示的当前URL . 所有这些方法都使用Location对象,它是Window对象的属性 . 您可以创建一个具有当前URL的新Location对象,如下所示 .

    var currentLocation = window.location;
    

    Basic Structure of a URL

    <protocol>//<hostname>:<port>/<pathname><search><hash>
    

    enter image description here

    • Protocol - 指定用于访问Internet上资源的协议名称 . (HTTP(不使用SSL)或HTTPS(使用SSL))

    • hostname - 主机名指定拥有该资源的主机 . 例如,www.stackoverflow.com . 服务器使用主机名提供服务 .

    • port - 用于识别Internet或其他网络消息到达服务器时要转发到的特定进程的端口号 .

    • pathname - 该路径提供有关Web客户端要访问的主机中的特定资源的信息 . 例如,stackoverflow.com / index.html .

    • query - 查询字符串在路径组件之后,并提供资源可用于某种目的的信息字符串(例如,作为搜索的参数或要处理的数据) .

    • hash - URL的锚点部分,包括井号(#) .

    使用这些Location对象属性,您可以访问所有这些URL组件

    • hash - 设置或返回URL的锚点部分 .

    • host - 设置或返回URL的主机名和端口 .

    • hostname - 设置或返回URL的主机名 .

    • href - 设置或返回整个URL .

    • pathname - 设置或返回URL的路径名 .

    • port - 设置或返回服务器用于URL的端口号 .

    • protocol - 设置或返回URL的协议 .

    • search - 设置或返回URL的查询部分

    现在如果您想要更改页面或将用户重定向到其他页面,您可以使用Location对象的 href 属性,如下所示

    您可以使用Location对象的href属性 .

    window.location.href = "http://www.stackoverflow.com";
    

    Location Object 也有这三种方法

    • assign() - 加载新文档 .

    • reload() - 重新加载当前文档 .

    • replace() - 用新文档替换当前文档

    您也可以使用assign()和replace方法重定向到这些其他页面

    location.assign("http://www.stackoverflow.com");
    
    location.replace("http://www.stackoverflow.com");
    

    How assign() and replace() differs - replace()方法和assign()方法()之间的区别在于replace()从文档历史记录中删除当前文档的URL,意味着无法使用"back"按钮导航回到原始文件 . 因此,如果要加载新文档,请使用assign()方法,并希望选择导航回原始文档 .

    您也可以使用 jQuery 更改位置对象href属性

    $(location).attr('href',url);
    

    因此,您可以将用户重定向到其他网址 .

  • 74

    使用:

    // window.location
    window.location.replace('http://www.example.com')
    window.location.assign('http://www.example.com')
    window.location.href = 'http://www.example.com'
    document.location.href = '/path'
    
    // window.history
    window.history.back()
    window.history.go(-1)
    
    // window.navigate; ONLY for old versions of Internet Explorer
    window.navigate('top.jsp')
    
    
    // Probably no bueno
    self.location = 'http://www.example.com';
    top.location = 'http://www.example.com';
    
    // jQuery
    $(location).attr('href','http://www.example.com')
    $(window).attr('location','http://www.example.com')
    $(location).prop('href', 'http://www.example.com')
    
  • 69

    那么,问题是如何制作重定向页面,而不是如何重定向到网站?

    您只需要使用JavaScript即可 . 这是一些将创建动态重定向页面的小代码 .

    <script>
        var url = window.location.search.split('url=')[1]; // Get the URL after ?url=
        if( url ) window.location.replace(url);
    </script>
    

    所以说你只需把这个片段放到你网站上的 redirect/index.html 文件中就可以这样使用了 .

    http://www.mywebsite.com/redirect?url=http://stackoverflow.com

    如果您转到该链接,它会自动将您重定向到 stackoverflow.com .

    链接到文档

    And that's how you make a Simple redirect page with JavaScript

    编辑:

    还有一点需要注意 . 我在我的代码中添加了 window.location.replace ,因为我认为它适合重定向页面,但是,你必须知道当使用 window.location.replace 并且你被重定向时,当你按下浏览器中的后退按钮时它将 not 回到重定向页面,并且它会回到之前的页面,看看这个小小的演示事物 .

    例:

    流程:store home => redirect page to google => google当google:google => back button in browser => store home

    所以,如果这符合您的需求,那么一切都应该没问题 . 如果要在浏览器历史记录中包含重定向页面,请将其替换为此

    if( url ) window.location.replace(url);
    

    if( url ) window.location.href = url;
    
  • 53

    标准“vanilla”JavaScript方式重定向页面:window.location.href ='newPage.html';


    If you are here because you are losing HTTP_REFERER when redirecting, keep reading:


    该以下部分适用于那些使用 HTTP_REFERER 作为许多安全措施之一的人(虽然它不是Internet Explorer 8或更低,但在使用任何形式的JavaScript页面重定向(location.href等)时这些变量都会丢失 .

    下面我们将实现IE8及更低版本的替代方案,以便我们不会丢失HTTP_REFERER . 否则你几乎总是可以简单地使用window.location.href .

    针对 HTTP_REFERER (URL粘贴,会话等)进行测试有助于判断请求是否合法 . ( Note: 还有解决这些引用者的方法,如评论中的droop链接所述)


    简单的跨浏览器测试解决方案(回退到Internet Explorer 9和所有其他浏览器的window.location.href)

    Usage: redirect('anotherpage.aspx');

    function redirect (url) {
        var ua        = navigator.userAgent.toLowerCase(),
            isIE      = ua.indexOf('msie') !== -1,
            version   = parseInt(ua.substr(4, 2), 10);
    
        // Internet Explorer 8 and lower
        if (isIE && version < 9) {
            var link = document.createElement('a');
            link.href = url;
            document.body.appendChild(link);
            link.click();
        }
    
        // All other browsers can use the standard window.location.href (they don't lose HTTP_REFERER like Internet Explorer 8 & lower does)
        else { 
            window.location.href = url; 
        }
    }
    
  • 50

    使用Javascript:

    window.location.href='www.your_url.com';
    window.top.location.href='www.your_url.com';
    window.location.replace('www.your_url.com');
    

    jQuery的:

    var url='www.your_url.com';
    $(location).attr('href',url);
    $(location).prop('href',url);//instead of location you can use window
    
  • 50

    一个人不只是使用jQuery重定向

    jQuery不是必需的,window.location.replace(...)将最好地模拟HTTP重定向 .

    window.location.replace(...) 比使用 window.location.href 更好,因为 replace() 不会将原始页面保留在会话历史记录中,这意味着用户不会陷入永无止境的后退按钮惨败 .

    如果要模拟某人点击某个链接,请使用location.href如果要模拟HTTP重定向,请使用location.replace

    For example:

    // similar behavior as an HTTP redirect
    window.location.replace("http://stackoverflow.com");
    
    // similar behavior as clicking on a link
    window.location.href = "http://stackoverflow.com";
    
  • 42

    警告:此答案仅作为可能的解决方案提供;它显然不是最好的解决方案,因为它需要jQuery . 相反,更喜欢纯JavaScript解决方案 .

    $(location).attr('href', 'http://stackoverflow.com')
    
  • 42

    如果您对自己想做的事情有一点描述性,那将会有所帮助 . 如果您尝试生成分页数据,则有一些选项可用于执行此操作 . 您可以为希望能够直接访问的每个页面生成单独的链接 .

    <a href='/path-to-page?page=1' class='pager-link'>1</a>
    <a href='/path-to-page?page=2' class='pager-link'>2</a>
    <span class='pager-link current-page'>3</a>
    ...
    

    请注意,示例中的当前页面在代码和CSS中的处理方式不同 .

    如果你想通过AJAX改变分页数据,这就是jQuery的用武之地 . 你要做的是为每个对应不同页面的锚标签添加一个点击处理程序 . 此单击处理程序将调用一些jQuery代码,通过AJAX获取下一页并使用新数据更新表 . 下面的示例假定您有一个返回新页面数据的Web服务 .

    $(document).ready( function() {
        $('a.pager-link').click( function() {
            var page = $(this).attr('href').split(/\?/)[1];
            $.ajax({
                type: 'POST',
                url: '/path-to-service',
                data: page,
                success: function(content) {
                   $('#myTable').html(content);  // replace
                }
            });
            return false; // to stop link
        });
    });
    
  • 35

    这适用于每个浏览器:

    window.location.href = 'your_url';
    
  • 13425

    原始问题 - “如何重新使用JQUERY”,HANS THE ANSWER IMPLEMENTS JQUERY >>免费使用案例

    要只使用JavaScript重定向到页面:

    window.location.href = "/contact/";
    

    或者如果您需要延迟:

    setTimeout(function () {
      window.location.href = "/contact/";
    }, 2000);   // Time in milliseconds
    

    jQuery允许您轻松地从网页中选择元素 . 您可以在页面上找到任何想要的内容,然后使用jQuery添加特效,对用户操作做出反应,或者显示和隐藏您选择的元素内部或外部的内容 . 所有这些任务都从了解how to select an element or an event开始 .

    $('a,img').on('click',function(e){
             e.preventDefault();
             $(this).animate({
                 opacity: 0 //Put some CSS animation here
             }, 500);
             setTimeout(function(){
               // OK, finished jQuery staff, let's go redirect
               window.location.href = "/contact/";
             },500);
         });
    

    想象一下有人写了10000行代码的脚本/插件?!好吧,使用jQuery,您只需一两行即可连接到此代码 .

  • 38

    我也认为 location.replace(URL) 是最好的方法,但是如果你想通知搜索引擎你的重定向(他们不分析JavaScript代码以查看重定向),你应该将 rel="canonical" 元标记添加到你的网站 .

    添加带有HTML刷新元标记的noscript部分也是一个很好的解决方案 . 我建议你用这个JavaScript redirection tool来创建重定向 . 它还具有Internet Explorer支持以传递HTTP引用者 .

    没有延迟的示例代码如下所示:

    <!-- Place this snippet right after opening the head tag to make it work properly -->
    
    <!-- This code is licensed under GNU GPL v3 -->
    <!-- You are allowed to freely copy, distribute and use this code, but removing author credit is strictly prohibited -->
    <!-- Generated by http://insider.zone/tools/client-side-url-redirect-generator/ -->
    
    <!-- REDIRECTING STARTS -->
    <link rel="canonical" href="https://yourdomain.com/"/>
    <noscript>
        <meta http-equiv="refresh" content="0;URL=https://yourdomain.com/">
    </noscript>
    <!--[if lt IE 9]><script type="text/javascript">var IE_fix=true;</script><![endif]-->
    <script type="text/javascript">
        var url = "https://yourdomain.com/";
        if(typeof IE_fix != "undefined") // IE8 and lower fix to pass the http referer
        {
            document.write("redirecting..."); // Don't remove this line or appendChild() will fail because it is called before document.onload to make the redirect as fast as possible. Nobody will see this text, it is only a tech fix.
            var referLink = document.createElement("a");
            referLink.href = url;
            document.body.appendChild(referLink);
            referLink.click();
        }
        else { window.location.replace(url); } // All other browsers
    </script>
    <!-- Credit goes to http://insider.zone/ -->
    <!-- REDIRECTING ENDS -->
    
  • 193

    ECMAScript 6 jQuery,85字节

    $({jQueryCode:(url)=>location.replace(url)}).attr("jQueryCode")("http://example.com")
    

    请不要't kill me, this is a joke. It'开个玩笑 . 这是个玩笑 .

    这确实“提供了问题的答案”,因为它要求“使用jQuery”的解决方案,在这种情况下需要以某种方式强制它进入等式 .

    Ferrybig显然需要解释的笑话(仍在开玩笑,我确信评论表上的选项有限),所以不用多说:

    其他答案是在 locationwindow 对象上不必要地使用jQuery的 attr() .

    这个答案也滥用它,但是更加荒谬 . 它使用 attr() 来检索设置位置的函数,而不是使用它来设置位置 .

    该函数名为 jQueryCode ,即使没有关于它的jQuery,调用函数 somethingCode 也很可怕,特别是当某些东西甚至不是一种语言时 .

    “85字节”是对Code Golf的引用 . 高尔夫显然不是你应该在代码高尔夫之外做的事情,而且这个答案显然不是高尔夫球 .

    基本上,畏缩 .

相关问题