36
votes

When I use window.open("www.google.com", "_blank");

window.open("www.google.com", "_blank");

A new tab is opened, but the url isn't "www.google.com", it's "=url-i-was-at=/www.google.com".

This is a snippet of the code (and the only relevant code). http://jsfiddle.net/FUYTY/

In jsfiddle it behaves a bit differently, but still doesn't work as it should.

What am i doing wrong?

4
www.google.com would be a local path, referring to for example a directory of the same name on your server. What you you need to link to an external domain instead is an absolute URL, so something like http://www.google.com/.CBroe
Not sure why this is being so heavily downvoted. It's a valid question with a clear solution.Alex

4 Answers

31
votes

You wanted to access the root document of server www.google.com, which is done using the url https://www.google.com/. You provided a relative url for document www.google.com instead.

Keep in mind that window.open accepts both relative and absolute urls, so it can't assume you left out https:// as it does when you use www.google.com in the address bar.


Maybe an example will help. Say the current page is http://www.example.com/dir/foo.html.

  • window.open("popup.html", "_blank") opens
    http://www.example.com/dir/popup.html.
  • window.open("www.google.com", "_blank") therefore opens
    http://www.example.com/dir/www.google.com.

The browser has no way of knowing you actually wanted https://www.google.com/ when you said you wanted http://www.example.com/dir/www.google.com since the latter could be valid.

14
votes

You have to prepend http:// in your url:

$(document).ready(function () {
    $('#mybtn').on('click', function () {
        window.open("http://www.google.com", '_blank');
    });
});

Fix: http://jsfiddle.net/FUYTY/4/

5
votes

Try adding http:// beforehand (see Fiddle http://jsfiddle.net/lkritchey/FUYTY/3/)

$( document ).ready(function() {
  $('#mybtn').on('click', function() {
      window.open("http://www.google.com", '_blank');   
  });
});

Some more information: If you include a '/' beforehand, it appends your string to the root URL. If you just list the string, it appends it to the current full URL. If you include either http:// or https:// it knows to use only what you put in your string (i.e. http://www.google.com)

3
votes

Preface your urls with http://