Relative URL to a different port number in a hyperlink?

It would be nice if this could work, and I don't see why not because : is a reserved character for port separation inside the URI component, so the browser could realistically interpret this as a port relative to this URL, but unfortunately it doesn't and there's no way for it to do that.

You'll therefore need Javascript to do this;

// delegate event for performance, and save attaching a million events to each anchor
document.addEventListener('click', function(event) {
  var target = event.target;
  if (target.tagName.toLowerCase() == 'a')
  {
      var port = target.getAttribute('href').match(/^:(\d+)(.*)/);
      if (port)
      {
         target.href = window.location.origin;
         target.port = port[1];
      }
  }
}, false);

Tested in Firefox 4

Fiddle: http://jsfiddle.net/JtF39/79/


Update: Bug fixed for appending port to end of url and also added support for relative and absolute urls to be appended to the end:

<a href=":8080/test/blah">Test absolute</a>
<a href=":7051./test/blah">Test relative</a>

How about these:

Modify the port number on click:

<a href="/other/" onclick="javascript:event.target.port=8080">Look at another port</a>

However, if you hover your mouse over the link, it doesn't show the link with new port number included. It's not until you click on it that it adds the port number. Also, if the user right-clicks on the link and does "Copy Link Location", they get the unmodified URL without the port number. So this isn't ideal.

Here is a method to change the URL just after the page loads, so hovering over the link or doing "Copy Link Location" will get the updated URL with the port number:

<html>
<head>
<script>
function setHref() {
document.getElementById('modify-me').href = window.location.protocol + "//" + window.location.hostname + ":8080/other/";
}
</script>
</head>

<body onload="setHref()">
<a href="/other/" id="modify-me">Look at another port</a>
</body>
</html>

You can do it easily using document.write and the URL will display correctly when you hover over it. You also do not need a unique ID using this method and it works with Chrome, FireFox and IE. Since we are only referencing variables and not loading any external scripts, using document.write here will not impact the page load performance.

<script language="JavaScript">
document.write('<a href="' + window.location.protocol + '//' + window.location.hostname + ':8080' + window.location.pathname + '" >Link to same page on port 8080:</a> ' );
</script>

Tags:

Html