是否有一种JavaScript方法可以重定向这两种方法:
url = 'www.google.com';
url = 'https://www.google.com';
因为接缝window.open(url)
需要在其前面放置http
,否则它会重定向到mysite.com/wwwgoogle.com
或者我应该使用其他方法重定向?
该解决方案将用于用户输入的网址,因此我需要为尽可能多的输入“样式”提供便利。
答案 0 :(得分:4)
if (!url.startsWith('http://') && !url.startsWith('https://'))
url = window.location.protocol + '//' + url;
感谢Rajesh发表评论
答案 1 :(得分:4)
您甚至可以覆盖window.open()
功能,如下所示任何不以http
或https
此功能开头的网址都附加http和重定向
请找到以下代码
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");
答案 2 :(得分:2)
另一种方法是使用regex
/^http(s?):\/\//
function hasProtocol(url) {
var regex = /^http(s?):\/\//;
return regex.test(url)
}
function appendProtocol(url) {
console.log("parsing url: ", url)
// Take your site's protocol instead of any default value
return window.location.protocol + "//" + url;
}
function parseURL(url) {
return hasProtocol(url) ? url: appendProtocol(url);
}
console.log(parseURL('www.google.com'))
console.log(parseURL('http://www.google.com'))
console.log(parseURL('https://www.google.com'))