JavaScript用户输入URL不持有我的域

JavaScript userinput URL without holding my domain

本文关键字:我的 用户 输入 URL JavaScript      更新时间:2023-09-26

我在使用JavaScript时遇到了一点麻烦。我的问题是我有一个用户输入框(用户将在其中输入URL)和一个按钮(当单击时,它将打开用户在输入框中键入的URL)。

下面是我的代码:
<input type="text" id="userurlbox"/>
<button type="button" onClick="myFunction()">Open URL</button>
<script>
function myFunction()
{
var x = document.getElementById('userurlbox').value;
if (x == "")
{
alert('Please enter a URL');
}
else
{
window.open(x ,'_blank');
}
</script>
问题是URL是这样打开的:
http://mywebsite.com/USERURL

我希望它像这样打开:

http://USERURL

这段代码只在'http://' '尚未包含时添加它:

function myFunction() {
        var x = document.getElementById('userurlbox').value; 
        if (x == "") {
            alert('Please enter a URL');
        }
        else {
            if (x.substr(0,4).toLowerCase() === 'http') { // only test first 4 characters as we want to allow both http:// and https://
                window.open(x ,'_blank');
            }
            else {
                window.open('http://'+x);
            }
        }
    }

我刚刚测试了,您需要在window.open

中包含'http://'
<input type="text" id="userurlbox"/>
<button type="button" onClick="myFunction()">Open URL</button>
<script>
function myFunction(){
var x = document.getElementById('userurlbox').value;
    x = x.replace('http://'.''); // remove  http:// just in-case it is there
    if (x == "")
    {
        alert('Please enter a URL');
    }    
     else
    {
       window.open('http://' + x ,'_blank');
    }
}
</script> 

我不确定是否可以使用窗口覆盖相对/绝对url行为。打开函数,所以一个可行的解决方案是检查url是否以https开头?://如果不是,则在前面加上'//'。以//开头的url将始终被视为绝对的。