-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
  • 12,158
  • 7
  • 41
  • 68
ymmx
  • 4,769
  • 5
  • 32
  • 64

5 Answers5

3

Please ensure you add the http for external websites:

window.location.href = "http://www.youtube.com";
o--oOoOoO--o
  • 770
  • 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
  • 434
  • 1
  • 5
  • 16
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
  • 12,158
  • 7
  • 41
  • 68
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
  • 2,142
  • 1
  • 16
  • 30
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
  • 14,342
  • 6
  • 49
  • 80