Reputation: 13
I am currently working on a URL Shortener for the website Scratch, the intended functionality is that if you navigate to a certain URL on my website (gobo.cf) it will take you to a certain project page.
For Example: If you go to http://gobo.cf/?to=165451669 it should redirect to https://scratch.mit.edu/projects/165451669/ but instead, it goes to https://scratch.mit.edu/projects/undefined.
<!DOCTYPE html>
<head>
<title>Gobo Redirect</title>
<script>
var projectid = window.location.hash.split('?to=')[1]
console.log(projectid)
var redirect = "https://scratch.mit.edu/projects/" + projectid
console.log(redirect)
</script>
</head>
<body onload="window.location = redirect;">
</body>
I have tried a number of solutions but whatever I try it always ends up redirecting to https://scratch.mit.edu/projects/undefined.
Upvotes: 0
Views: 92
Reputation: 4069
You don't have a hash
item in the location object. Hash is used when your URL looks like https://gobo.cf/foo#bar?to=12345
(note the #
character). If you use search
(or href
), you'll have better results, like this:
<!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>
The code I added in the onload will wrap your redirect in a function that gets called after 10 seconds so you could put a breakpoint inside chrome console and step through it. You can change the slowItDown
variable to enable or disable that and give yourself time to set the breakpoint the first time.
Upvotes: 2