0

I have the following javascript code, I redirect old link to a new one dynamically.

Sometimes newLink does not exist, and instead of getting 404 page, I want to custom my own page if URL was not found.

Any idea how to add this condition in my code please ?

<script>
setTimeout(function(){
 $('a[href="oldLink"]').attr('href','dir/newLink)
 }, 1000);
</script>

EDIT : I am running this code on Rstudio, I am new to javascript, I don't have a server because I am producing HTML pages using Rmarkdown locally.

Thanks !

Geek
  • 189
  • 3
  • 13
  • That's a typical task on the server-side. – Teemu Jun 06 '18 at 10:31
  • you can edit your default 404 page from your webserver settings – Lelio Faieta Jun 06 '18 at 10:31
  • Actually I am running this code on Rstudio, I am new to javascript, I don't have a server because I am producing html pages using Rmarkdown locally – Geek Jun 06 '18 at 10:32
  • Javascript is running on client side, and your client dont know when the server is running or not. The only way to do it, is to test via an ajax request if the server is available – YingYang Jun 06 '18 at 10:34
  • Just to say, `.attr('href','dir/newLink)` there's a`'` missing. Anyway I agree that's something to be done server-side: https://stackoverflow.com/questions/3397868/custom-404-error-issues-with-apache – Takit Isy Jun 06 '18 at 11:12
  • Thanks, yeah I forget to add it here, as for me I work locally with static folder, I dont have a server – Geek Jun 06 '18 at 11:25

1 Answers1

1

You can achieve it by the following code. There is one drawback that you have to always check if the link exist or not, if it is ok for you then this is the perfect solution for you.

$('body').append('<div id="temp-div" style="display:none"></div>');
    var url = 'dir/newLink';
    $('#temp-div').load(url, function (a, b, c) {
    if (c.status == 404)
        $('a[href="oldLink"]').attr('href', 'YOUR_CUSTOM_404_LINK');
    else
       $('a[href="oldLink"]').attr('href', url);
    $('#temp-div').remove();
});
Pang
  • 9,564
  • 146
  • 81
  • 122
Abhay Prince
  • 2,032
  • 1
  • 15
  • 17
  • Thanks for your answer , That seems very coherent, I tried your code for non existing link but I have always the 404 error page. May be the c.status could have other error values ? – Geek Jun 06 '18 at 11:10
  • 404 means Page/link not found - For non-existent link it will always give HttpStatus 404 – Abhay Prince Jun 06 '18 at 11:11
  • I am working locally, I don't have a localhost, I have static html folder this is my directory. Is c.status always supposed to work even with static HTML pages ? – Geek Jun 06 '18 at 11:24
  • Else is working but the IF condition is not (I redirect link to google page if page not found but I find always 404 page) – Geek Jun 06 '18 at 11:27
  • Maybe the condition should be wether the url exists or not on that directory or not I tried url.exists() instead of c.status ==404 but it did not work – Geek Jun 06 '18 at 11:36