Redirecting in Javascript

Asked

Viewed 51 times

2

Because it does not 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()">
</form>

  • I edited the answer and improved the script to not give errors with spaces and with https also

3 answers

0

On the line you put

     return location.href = url;

You must put, dear want to replace the current page by the url typed by the user

    window.open(url, _self);
  • with the function window.open(url) it opens another window and does not redirect to the url.. did not resolve...

  • I edited the answer to better visualize.

0

0


Put in a conditional function, to check if http:// or https:// was typed, 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;
}
  • it worked !! thanks.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.