Languages
[Edit]
EN

JavaScript - open link in new tab

5 points
Created by:
Zoya-Gaines
263

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

Quick solution:

// ONLINE-RUNNER:browser;

var site = window.open('https://dirask.com', '_blank');

site.opener = null; // prevents against JavaScript code level access from opened page to opening page

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 click simulation example

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

// ONLINE-RUNNER:browser;

var a = document.createElement('a');

a.setAttribute('href', 'https://dirask.com');
a.setAttribute('target', '_blank');
a.setAttribute('rel', 'noopener noreferrer'); // prevents against JavaScript code level access from opened page to opening page

a.click();

Avoiding blocking by web browser example

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

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <span onclick="var site = window.open('https://dirask.com', '_blank'); site.opener = null;">
    Click me and open new tab
  </span>
</body>
</html>

 

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