[英]redirecting page based on own url
我想根据我的网址重定向页面。 例如,如果我访问www.home.com,我想将其重定向到www.home.com/home。 我有一个代码,但是我的网站上有一些错误。
以下是我现在正在使用的代码,我希望仅当我将www.home.com放到该JS中时,才能激活该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/
根据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>
<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
它将重定向到其他页面。
仅获取URL的开头部分,再加上“首页”
<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>
将标签放在您需要链接的任何地方。
让浏览器完成工作,然后检查主机名:
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
-Tag如果你只是把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使用'fiddle.jshell.net'作为URL,所以使用了Fiddle fiddle.
部分将被删除,仅主要部分被检查,如果它是jshell,它将被重定向并正常工作,但是'home.com/home'不存在,它只是一个示例域,因此显然不显示任何相关内容。
编辑
我发现了一些深入的信息。
如果您在href内没有http://
,它将使用window.location
,因此,如果您将此技术与其他给定的href
一起使用,请当心。
另外,我还添加了一个pathname
检查,因此如果是重定向页面,它就不会重定向。
遵循不a
-Tag部分的代码(因为此处不需要):
if (window.location.hostname.replace( 'www.', '' ) == 'host.com' && window.location.pathname.replace( '/', '' ).length == 0 ) {
window.location.href = 'host.com/home';
}
如果您的第一个/
后面的单词不止一个,例如home/login/now
replace( /\\/(.*)?/g, '' )
也可以使用replace( /\\/(.*)?/g, '' )
来代替replace( '/', '' )
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.