In this blog, we will look at a very simple HTML tag that can come in very handy at solving certain problems that developers encounter somewhere down their career.
What is the HTML base tag?
HTML base tag is a pretty simple tag which is not known by many. What it does is that it specifies the base URL for the all the relative URLs in the document. For example, if you have an
img tag with a relative
/images/logo.png and if you have set a
base tag with href as
href='https://xencov.com' then the browser will make a call to
https://xencov.vom/images/logo.png to load the image instead of picking up the
host as the base URL automatically.
When to use it?
Many developers won't know about the
base tag untill they actually get stuck at a problem that can be solved easily by the
Lets take an example, you want to load a webpage into an
iframe but you realize that many sites don't allow them to be opened into a frame object like
iframe, etc. by sending a header called
X-Frame-Options with the value
same-origin header value basically means that the page can only be opened in a frame on the same origin/host and not a different host which would be the case with you.
To overcome this, you would need to make an HTTP request to the webpage URL and get the page HTML as string which you will then write to the
iframe. This will allow you to bypass the
X-Frame-Options header problem but now you encounter another issue. You see that all the resources on the webpage with a relative URL are broken, this happens because there is no host set on the src for
iframe to direct the relative URL's too and it picks up your current host instead.
The first approach for anyone who isn't aware of the
base tag would be to rewrite all the relative URL's in the document by using a RegExp, which is what I did in the first place. While that would solve the problem, its not a neat solution when a even better solution exists which is the
You can just place a
base tag with the correct host inside the
Let me know if it works for you and or if you already knew it.
Hope this helps!