-3

I am trying to go to external url from my website with this code

var embed = "www.youtube.com";  
console.log(embed);
window.location.assign(embed);

However, the webpage doesn't go to the the link in var embed but go instead to Mywebsite/thepageofthatcode/www.youtube.com

window.location = "www.youtube.com";
window.location.href = "www.youtube.com";

I didn't get why is this happening?

Sagar V
  • 11,606
  • 7
  • 43
  • 64
ymmx
  • 4,302
  • 5
  • 23
  • 60

5 Answers5

3

Please ensure you add the http for external websites:

window.location.href = "http://www.youtube.com";
o--oOoOoO--o
  • 752
  • 4
  • 7
1

Add the protocol to make it work. Without the protocol it will search for www.youtube.com under your domain which is why it is redirecting to that way. Try

window.location.href = 'https://www.youtube.com';
A. Wong
  • 385
  • 1
  • 4
  • 15
1

You should use the protocol before the url. Otherwise, the browser will think that it is a path.

var embed = "http://www.youtube.com";  
console.log(embed);
window.location.assign(embed);
Sagar V
  • 11,606
  • 7
  • 43
  • 64
1

Add the protocol to make it work. Without the protocol, it thinks that www.youtube.com is a part of your website.

This is the problem. But here's a better why to fix it:

// Use RegExp to test if embed already has the protocol
// If not, prepend it to embed.
if (!/^https?:\/\//i.test(embed))
    embed = 'http://' + embed;

window.location.href = embed;

RegExp guide

URL Syntax

Justin Taddei
  • 1,799
  • 1
  • 14
  • 26
1

This solves the problem, only need to add the http part to the url

var embed = "http://www.youtube.com";  
window.open(embed);
lealceldeiro
  • 13,596
  • 5
  • 44
  • 76