Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavasScript method to redirect most urls: (www., http://, https://)

Is there a JavaScript method that would redirect both of these:

url = 'www.google.com';
url = 'https://www.google.com';

As it seams window.open(url) requires to have the http in front of it or it would redirect to mysite.com/wwwgoogle.com

Or should I use another method to redirect?

The solution would be used for user inputted urls so I need to facilitate for as much input "styles" as possible.

like image 546
Иво Недев Avatar asked Feb 22 '26 23:02

Иво Недев


1 Answers

You can even override window.open() function as below so any url which does not starts with http or https this function append http and redirect

please find below code

window.open = function (open) {
        return function (url, name, features) {
        url = addhttp(url);
        return open.call(window, url, name, features);
    };
}(window.open);

function addhttp(url) {
   if (!/^(f|ht)tps?:\/\//i.test(url)) {
      url = "http://" + url;
   }
   return url;
}

window.open("google.com");
window.open("https://www.google.com");
like image 74
Curiousdev Avatar answered Feb 24 '26 11:02

Curiousdev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!