JavaScript Redirect

Posted on

Question :

Why does not it redirect to the page typed in URL?

function irPara(url){
    url = document.irParaURL.URL.value;
    return location.href = url;
<form name="irParaURL">
    <label>Dígite um site:</label>
    <input type="text" name="URL" value="">
    <input type="button" value="Ir" onclick="irPara()">


Answer :

Put a conditional function in the function to check whether http:// or https:// was entered, if it was not concatenated in the url

function irPara(url){
    url = document.irParaURL.URL.value;
    url = url.trim(); //Remove espaços em branco no inicio e fim
    var httpString = "http://";
    var httpsString = "https://";
    if (url.substr(0, httpString.length).toLowerCase() !== httpString && url.substr(0, httpsString.length).toLowerCase() !== httpsString)
        url = httpString + url;

    return location.href = url;


Remove the return.
If it is an external link, you need to add http: // or https: //

Change window.location.href does not redirect to new page


On the line you put

     return location.href = url;

You should put, dear, you want to replace the current page with the url you typed, _self);


Leave a Reply

Your email address will not be published. Required fields are marked *