根据自己的网址重定向页面

时间:2015-06-17 08:17:39

标签: javascript

我想根据我的网址重定向我的网页。例如如果我访问www.home.com我想将其重定向到www.home.com/home。我有一个代码,但它在我的网站上有一些错误。

下面是我正在使用的代码我希望这个JS仅在我放入www.home.com时激活如何将其合并到这个JS中?

JS:

<script>
    setTimeout(function(){
        window.location.href="http://home.com/"; // The URL that will be redirected too.
    }, 0); // The bigger the number the longer the delay.
</script>

更新:

 <script>
var a = document.createElement('a');
    a.href = window.location.href;

if (a.hostname.replace('http://www.', '') == 'frederiksminde.com') {

    window.location.href = 'http://www.frederiksminde.com/da/';

}
  </script>

此代码工作正常,但当我访问http://www.frederiksminde.com/da/的子页面时,它还会将我重定向到frederiksminde.com/da /

4 个答案:

答案 0 :(得分:0)

根据unikorn的评论:

<script>
    setTimeout(function(){
        if (window.location.href=="http://www.home.com"){
            window.location.href = "http://www.home.com/home"
        }
    }, 0); // The bigger the number the longer the delay.
</script>

答案 1 :(得分:0)

  <script>
        setTimeout(function(){
           if(window.location.href == "http://www.home.com"){ //window.location.href returns current page url 
              window.location.href="http://www.home.com/home";
           }
        }, 0); // The bigger the number the longer the delay.
  </script>
如果条件检查当前网址是www.home.com或www.home.com/home

,则在上面的代码中

它会重定向到其他页面。

答案 2 :(得分:0)

只获取网址的开头部分,加上“主页”

<script>
document.ondomcontentready = function () {
    var slice = location.href.split('/');
    var domain = slice[1] ? slice[0] : slice[2];
    var final = domain + '/home';
    setTimeout(function () {
        location.href = final;
    }
    }, 0);
}
</script>

将标记放在您需要链接的任何位置。

答案 3 :(得分:0)

让浏览器完成工作并检查主机名:

var a = document.createElement('a');
    a.href = window.location.href;

if (a.hostname.replace('www.', '') == 'host.com') {

    window.location.href = 'host.com/home';

}

参考:http://www.w3schools.com/jsref/obj_location.asp

所以根据裁判你也可以使用window.location.hostname,但我想向你展示一个a标记 - 如果你只是采用href - 部分,您也可以像a.href.hostname一样使用它。

我想提供一个JSFiddle示例,但JSFiddle现在还没有保存。如果你想在JSFiddle上试试这个,请使用以下代码:

var a = document.createElement('a');
    a.href = window.location.href;

if (a.hostname.replace('fiddle.', '') == 'jshell.net') {

    window.location.href = 'host.com/home';

}

我使用一些不同代码的原因是,因为JSFiddle使用&#39; fiddle.jshell.net&#39;作为网址,因此fiddle.部分将被移除,只检查主要部分,如果它是jshell,它将重定向并且它正常工作,但是&#39; home.com/home& #39;它不存在,它只是一个示例域名,因此它显然没有显示任何相关内容。

修改

我发现了一些深入的信息。

如果您在href中没有http://,则需要window.location,因此如果您将此技术与其他href一起使用,请务必小心。

此外,我添加了pathname支票,因此如果它是重定向的网页,则不会重定向。

关注没有a - 代码部分的代码(因为此处不需要):

if (window.location.hostname.replace( 'www.', '' ) == 'host.com' && window.location.pathname.replace( '/', '' ).length == 0 ) {
    window.location.href = 'host.com/home';
}

而不是replace( '/', '' )如果您在replace( /\/(.*)?/g, '' )之后的第一个/之后只有一个字,那么您也可以使用home/login/now