0

I have an anchor tag in my application which points to an external website.

say; "<http://www.google.com'>>General Search<>" . User on clicking this link will be taken to google home page. I have links of these types in several pages of my application. All points to external websites. User is the one who actually inputs the href and we dynamically creates the link with that , And we are not providing any validation to check whether the url is a valid one.

Say ; if the user enters "somebadtextnotavalidurl" application will generate a link which looks like "<>somebadtextnotavalidurl<>" , Which on clicking will gives a 404 error.

My requirement is that i need to handle this link click in my page using javascript; If it is a valid url a new tab should be open for the url page and display the content, Else if it is a 404 then also a new tab should be open but instead of the default 404 error page that browser displays i need my own styled and formatted page should be displayed.

Jithin Kumar
  • 49
  • 1
  • 9

1 Answers1

1

Short answer: This really is not possible.

Long answer: You basically have two options, both bad.

1) Instead of using the actual URL your users enter, you need to prefix that URL with a server-side "handler" or "proxy" which runs on your domain, which takes the destination URL as a parameter. Let's say that it's called UrlForwarder.aspx. Then your links would point to /UrlForwarder.aspx?url=<actual url>. When clicked, the UrlForwarder.aspx reads the URL from the query-string, and tries to open it using an HttpClient of some sort. Based on the response headers (404, 200) then redirects the user to either the actual URL or your customized 404 page.

2) A client side only solution would be to attach an event handler to all links when the document loads. This event handler would then do an ajax request to the URL, check the response headers and if everything is OK, redirect the user to the url. Otherwise, redirect to your custom 404 page. There's a big caveat to this method which is the same origin policy (javascript cannot load documents from other domains, basically), which means that your javascript would not be allowed to load external websites. See more here: AJAX cross domain call

This can be circumvented with a configuration setting in most browers though.

Community
  • 1
  • 1
HaukurHaf
  • 13,522
  • 5
  • 44
  • 59