It will help users with http prepending annoyance without being intrusive. Just add this JavaScript code to your webpages with type="url"
<input>
elements, and everything will work automatically.
// Run a callback function after DOM is fully loaded
function domReady(callback) {
if (document.readyState != "loading") {
callback();
} else {
document.addEventListener("DOMContentLoaded", callback);
}
}
// Prepend https to url input field value if already not prepended by http or https
domReady(() => {
const urlInput = document.querySelectorAll('input[type="url"]');
for(i = 0; i < urlInput.length; i++) {
urlInput[i].addEventListener('change', function(){
let urlValue = this.value;
// If http or https isn't prepended as case insensitive characters and if the input field has any value
if (!urlValue.match(/^https?:/i) && urlValue.length) {
urlValue = "https://" + urlValue;
this.value = urlValue;
}
});
}
});
Advantages
- prepending
https://
if http
or https
isn't already prepended
in the input field value
- prepending
https://
even when there is http
or https
that isn't in the beginning
- automatically modifying value after users leave input field
- not adding
https://
if input field has no value
- working in a case insensitive manner
- automatically working on all url type input fields without requiring to modify HTML input field elements
Limitations
- adding
https://
in front of valid urls that start with any schemes
other than http
or https
such as ftp
and tel
which will cause those valid URLs to not work
PS: If you also want to change http
to https
, append this else if
statement to the last if
statement in the previous code.
else if (urlValue.match(/^http:/i)) {
urlValue = urlValue.replace(/^http:/i, "https:");
this.value = urlValue;
}
stackoverflow.com
really isnt a URL. It's just a host name... – Forefrontonsubmit
event. – Ebsenhttp
URLs are just one kind of URL.ftp://
,ssh://
,https://
,git://
are all common schemes for URLs. Thetype="url"
input doesn’t accept scheme-less URLs because of that: a scheme-less URL is not a URL and the assumed protocol depends on your application. – Theriot