I have a list of URLs that our users have entered for websites of various clients... I am loading this list from the server into a grid for the users to see... I made the URLs clickable by wrapping them with a href HTML tag... the problem is, sometimes the user enters urls without the http:// or www. prefix and so the browser treats them as relative URLs which are never ever the case because all these websites are for our clients and they are all external. Is there a way to force these URLs to be treated as absolute instead of relative?
Here is an example:
<a target='_blank' href='google.com'>google.com</a>
If you try this, you'll see that the browser will assume it is a relative path which shouldn't be the case.
Thanks
Solution:
I've chosen to check for '//' (because I don't know what the protocol is - could be http or https) and if not found, I assume it is an http website and I prefix the URL with that - so in short no way to force the browser to treat the hyperlinks as absolute
An absolute URL is the full URL, including protocol ( http / https ), the optional subdomain (e.g. www ), domain ( example.com ), and path (which includes the directory and slug). Absolute URLs provide all the available information to find the location of a page.
An absolute URL contains the entire address from the protocol (HTTPS) to the domain name (www.example.com) and includes the location within your website in your folder system (/foldernameA or /foldernameB) names within the URL. Basically, it's the full URL of the page that you link to.
An absolute URL contains all the information necessary to locate a resource. A relative URL locates a resource using an absolute URL as a starting point.
A local link (a link to a page within the same website) is specified with a relative URL (without the "https://www" part):
Links are found in nearly all web pages. Links allow users to click their way from page to page. HTML Links - Hyperlinks HTML links are hyperlinks.
The HTML <a> tag defines a hyperlink. It has the following syntax: The most important attribute of the <a> element is the href attribute, which indicates the link's destination. The link text is the part that will be visible to the reader. Clicking on the link text, will send the reader to the specified URL address.
How can I force the a tag to be absolute ? You can try to use window.location But the best is to validate the users' input. Prompt them to provide a valid url. If you prefix the URL with // it will be treated as an absolute one. For example: <a href="//google.com">Google</a>.
You can add //
before the url and it should work.
Like: //stackoverflow.com
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With