If you need a redirect from one domain to another but do not have access to the server (for example, on free blogging platforms), a redirect with Javascript may be the best solution.

How does redirecting work with Javascript?

Redirections in Javascript work by modifying properties in the location interface of the document in the browser. This interface is Document.location and Windows.location. and the property that stores the location is href. For example, the current location of a page can be obtained as follows:

let paginaActual = location.href;
console.log( paginaActual );

Result:

Result on the Firefox Javascript console.

Result on the Firefox Javascript console.

Then, to change that location and therefore redirect the current page, we just set a new location:

location.href = 'target URL';

But in practice this code would not be the best user experience.

Redirecting with Javascript. Practical example.

When it is necessary to make a redirect the most likely reason is that there was a change (domain, content, importance), then to give a better user experience we could:

  1. Wait for the page to load.
  2. Display a message that the content has changed location and wait x seconds for it to be read.
  3. Execute the redirection.

This can be done with this code:

<script type="text/javascript">
let targetURL = 'https://blogandweb.com'; // The target URL. Destination.
let wait   =  5; // The wait in seconds before executing the redirection.

function waitPageLoad(fn) {
    if (document.readyState !== 'loading') {
        fn();
    } else {
        document.addEventListener('DOMContentLoaded', fn);
    }
};

waitPageLoad( function(){
  	wait = parseInt(wait);
    setTimeout('location.href="'+targetURL+'"', wait*1000);
} );
</script>

Where you need to replace:

  • https://blogandweb.com – With your destination URL, the new URL. Don’t forget to add the protocol: http:// or https://. Other uses: You can redirect to an email: Example: “mailto:my@email.com”. Or to an anchor on the page. Example: “#footer”.
  • 5 – With the number of seconds before executing the redirection. It can be 0 so that there is no timeout.

Like any other Javascript code, you can place it directly between <head> and </head> or in an external .js function file.

Browser support

location.href is a very old property and well supported by all browsers. You can use it with peace of mind in production.

Conclusion

Redirecting with Javascript is perhaps not the most elegant way to solve a URL change, but there are situations where there is no other option and it turns out to be the best solution.