JavaScript - Url Forwarder

From NoskeWiki
Jump to navigation Jump to search


NOTE: This page is a daughter page of: JavaScript

You can use the call window.location.href to forward a user to another page, or see the current URL and pick out query parameters etc. Here's an example of forwarding to another page.

Simple Miles to Kilometers Converter


<!doctype html>
<html lang="en">
  <title>Url Fowarder (in JavaScript)</title>
  Forwarding you to different URL...<br><br>

  <i>INSTRUCTIONS</i>: Your URL on this page should end in "<b>#&lt;ANCHOR_ID&gt;</b>"<br>
  <i>EXAMPLE</i>: "<a href="url_forwarder_javascript.html#Status_Bar">url_forwarder_javascript.html#Status_Bar</a>"<br>

    var currentUrl = window.location.href;
    var idx = currentUrl.indexOf('#');
    if (idx <= 0) {
      window.alert('Wrong URL format to forward: ' + currentUrl + ' should end with: "#<ANCHOR_ID>"');
      console.log('Wrong URL format to forward: ' + currentUrl + ' should end with: "#<ANCHOR_ID>"');
    } else {
      var anchorId = currentUrl.substring(idx + 1);
      console.log('Forwarding using anchorId: ' + anchorId);
      window.location.href = "" + anchorId;


Code license
For all of the code on my site... if there are specific instruction or licence comments please leave them in. If you copy my code with minimum modifications to another webpage, or into any code other people will see I would love an acknowledgment to my site.... otherwise, the license for this code is more-or-less WTFPL (do what you want)! If only copying <20 lines, then don't bother. That said - if you'd like to add a web-link to my site or (better yet) the specific page with code, that's a really sweet gestures! Links to the page may be useful to yourself or your users and helps increase traffic to my site. Hope my code is useful! :)

See Also