Javascript URL缩短器/重定向到未定义的页面
我目前正在为网站Scratch开发一个URL缩短器,其预期功能是,如果您导航到我的网站(gobo.cf)上的某个URL,它会将您带到某个项目页面 例如:如果您转到,它应该重定向到,但它会转到Javascript URL缩短器/重定向到未定义的页面,javascript,Javascript,我目前正在为网站Scratch开发一个URL缩短器,其预期功能是,如果您导航到我的网站(gobo.cf)上的某个URL,它会将您带到某个项目页面 例如:如果您转到,它应该重定向到,但它会转到 戈波重定向 var projectid=window.location.hash.split(“?to=”)[1] console.log(projectid) 变量重定向=”https://scratch.mit.edu/projects/“+projectd console.log(重定向) 我尝试
戈波重定向
var projectid=window.location.hash.split(“?to=”)[1]
console.log(projectid)
变量重定向=”https://scratch.mit.edu/projects/“+projectd
console.log(重定向)
我尝试了许多解决方案,但无论我尝试了什么,结果总是重定向到。location对象中没有
散列项。当您的URL看起来像https://gobo.cf/foo#bar?to=12345
(注意#
字符)。如果您使用搜索
(或href
),您将获得更好的结果,如下所示:
<!DOCTYPE html>
<html>
<head>
<title>Gobo Redirect</title>
<script type="application/javascript">
// You can open Chrome inspector to "debug" and set breakpoints
// and can change this variable to help out with that.
var slowItDown = true;
function doRedirect() {
var hash = window.location.hash;
console.log( "Oh no, hash is empty!:", hash );
var search = window.location.search;
console.log( "Search is: ", search );
var projectid = search.split('?to=')[1];
console.log(projectid);
var redirect = "https://scratch.mit.edu/projects/" + projectid;
console.log(redirect);
}
</script>
</head>
<body onload="slowItDown ? setTimeout( doRedirect, 10000 ) : doRedirect();">
</body>
</html>
戈波重定向
//您可以打开Chrome inspector进行“调试”并设置断点
//可以改变这个变量来帮助解决这个问题。
var slowItDown=真;
函数doRedirect(){
var hash=window.location.hash;
log(“哦,不,散列是空的!:”,散列);
var search=window.location.search;
log(“搜索为:”,搜索);
var projectid=search.split('?to=')[1];
console.log(projectid);
变量重定向=”https://scratch.mit.edu/projects/“+Projectd;
控制台日志(重定向);
}
我在onload中添加的代码将把重定向包装在一个函数中,该函数在10秒后被调用,这样您就可以在chrome控制台中设置一个断点并逐步执行它。您可以更改slowItDown
变量以启用或禁用该变量,并给自己第一次设置断点的时间。从window.location.hash开始,但url中没有哈希,因此只返回未定义的。也许您需要window.location.search.split('?to=')
如果您需要,可以看看我为轻松处理查询字符串而构建的这个组件,它在这里和将来可能会很有用。
<!DOCTYPE html>
<html>
<head>
<title>Gobo Redirect</title>
<script type="application/javascript">
// You can open Chrome inspector to "debug" and set breakpoints
// and can change this variable to help out with that.
var slowItDown = true;
function doRedirect() {
var hash = window.location.hash;
console.log( "Oh no, hash is empty!:", hash );
var search = window.location.search;
console.log( "Search is: ", search );
var projectid = search.split('?to=')[1];
console.log(projectid);
var redirect = "https://scratch.mit.edu/projects/" + projectid;
console.log(redirect);
}
</script>
</head>
<body onload="slowItDown ? setTimeout( doRedirect, 10000 ) : doRedirect();">
</body>
</html>