1

This code (with HTTPS protocol), successfully opens https://www.google.com.

JSFiddle

<script>
    function openInNewTab() {
        var url = 'https://www.google.com';
        var win = window.open(url, '_blank');
        win.focus();
    }
</script>

<div onclick="openInNewTab();">OPEN LINK ON A NEW WINDOW</div>

But when I use this code (without HTTP protocol), it opens https://www.example.com/www.google.com instead.

JSFiddle

<script>
    function openInNewTab() {
        var url = 'www.google.com';
        var win = window.open(url, '_blank');
        win.focus();
    }
</script>

<div onclick="openInNewTab();">OPEN LINK ON A NEW WINDOW</div>

Is there a way to use Javascript to open an external website without HTTPS protocol?

3
  • 4
    you need to have a protocol when fetching cross domain ... at least //www.google.com - then the protocol will depend on the protocol of the page making the request (http or https) Commented Mar 14, 2017 at 2:39
  • Yes, otherwise the browser will assume that it is a relative path of the current domain. Commented Mar 14, 2017 at 2:40
  • 1
    Can you tell us why you do not want to use "HTTP protocol"? Commented Mar 14, 2017 at 3:06

3 Answers 3

3

Why not just use an external anchor tag with the target set to _blank?

E.g

<a href="http://www.google.com" target="_blank">OPEN LINK A NEW WINDOWS</a>

Although in this example, google will redirect to https because security

Sign up to request clarification or add additional context in comments.

Comments

2

A URL string without a protocol at the beginning (or the "protocol-relative shorthand" // for which there are good arguments to not use it) will be considered either an anchor URL if it begins with a hash, #fragment, or otherwise a relative URL. A relative URL just puts www.google.com on top of the current level of the path. If your location is http://www.example.com then that becomes http://www.example.com/www.google.com. Or if it's http://foo.net/bar/baz/quux.html, that becomes http://foo.net/bar/baz/www.google.com.

Comments

-1
var url = new URL('http://example.com');

Keep in mind that when you are opening http://google.com they have a redirect to their https protocol. Not much you can do about that.

1 Comment

Further notes which won't answer the question should be put into the comment section!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.