1

I need to use Javascript window.location.assign() to take input from a user in an inputbox and once a button is clicked the user will be taken to the URL they entered in that inputbox- I am having difficulty finding this online. I am assuming I would need to add a function to my script (not shown).

    <form style="padding-top: 20px;">
        URL: <input type="url" name="url">
        <input type="button" value="GO!" onclick="newUrl()">
    </form>
Bunny
  • 35
  • 8
  • Retrospectively, navigating users to arbitrary client-side input is a security concern. Application logic (residing on either frontend or backend) should at least sanitize the input. (Best if a whitelist is used) – DannyNiu Mar 09 '21 at 07:44

3 Answers3

2

First, instead of putting the function in "onclick" in the button, I suggest putting it on the form element's "onsubmit" handler. That way, a simple "Enter" key can also cause the navigation.

Second, since we're putting the callback on the form, the form's action should changed to 'javascript', like this:

<form style="padding-top 20px;" action="javascript://#" onsubmit="newUrl(this.elements['url'].value)">
    URL: <input type="text" name="url">
    <input type="submit" value="GO!">
</form>

I've put the url in the first parameter of the "newUrl" function, for ease of writing.

Finally, your "newUrl" function:

function newUrl(url) {
    window.location.assign(url);
}
E_net4
  • 27,810
  • 13
  • 101
  • 139
DannyNiu
  • 1,313
  • 8
  • 27
  • Thanks, Danny. I had tried other options that didn't work, so I didn't want to include them in my code posted here! Appreciate you not downvoting me. Still new to all! Thanks again- you explained it perfectly. – Bunny Nov 29 '18 at 05:18
1

Before using the window.location.assign I would like you to read this

https://developer.mozilla.org/en-US/docs/Web/API/Location/assign

The Location.assign() method causes the window to load and display the document at the URL specified.

If the assignment can't happen because of a security violation, a DOMException of the SECURITY_ERROR type is thrown. This happens if the origin of the script calling the method is different from the origin of the page originally described by the Location object, mostly when the script is hosted on a different domain.

If the provided URL is not valid, a DOMException of the SYNTAX_ERROR type is thrown.

Here is the what you can do to use it

function newUrl(){
  window.location.assign(document.getElementById("url").value);
}
 <form style="padding-top: 20px;">
        URL: <input type="url" name="url" id="url">
        <input type="button" value="GO!" onclick="newUrl()">
    </form>
Just code
  • 13,553
  • 10
  • 51
  • 93
0

Simple alternative

<form style="padding-top 20px;" onsubmit="this.action=document.getElementById('url').value">
  URL: <input type="text" id="url">
  <input type="submit" value="GO!">
</form>
mplungjan
  • 169,008
  • 28
  • 173
  • 236