Reputation: 189
This code (with HTTPS protocol), successfully opens https://www.google.com
.
<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.
<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?
Upvotes: 1
Views: 10359
Reputation: 607
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
.
Upvotes: 2
Reputation: 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.
Upvotes: -1
Reputation: 2308
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
Upvotes: 3