Languages
[Edit]
EN

JavaScript - open link in new tab

8 points
Created by:
Zoya-Gaines
653

In this short article, we would like to show how in JavaScript open some links in a new tab.

Quick solution:

or:

Notes:

  • opening pages from outside the domain can lead to attacks when we use _blank parameter,
  • many browsers blocks popupping windows this way - sometimes it is better to consider simple link in html code with target="_blank" attribute,
  • to avoid browser blocking effect it is good to run above action inside mouse click event function - check last example.

 

Read the next sections for more details.

 

Link with a click simulation example

Edit

In this approach, it is necessary to create a new link element and simulate clicking on it.

Note (in 2021): when we use target="_blank" attribute in links, in major modern web browsers, it is automatically used rel="noopener" attribute behaving to prevent vulnerabilities - check notification here.

Warning: for security reasons, it is important to use rel="noopener" attribute, even if some tools warns us about unnecessary attribute.

 

Avoiding blocking by web browser example

Edit

In this section, the open in new window action is run during onclick event to prevent blocking operation.

 

References

Edit
  1. https://html.spec.whatwg.org/multipage/links.html#link-type-noreferrer
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join