简体   繁体   中英

Open links on the page in a new tab - javascript

How can we make every link on the page be opened in a new tab?

thus every link redirection will go to new tab. and website will be safe at it's place

We can do this,

<a href="there_links.com" target="_blank">there_links.com</a>

But since user can add there own links in comments section which supports markdown.

Its hard to set target="_blank" on every link on a page. because these links will be popualted through markdown .

for example clicking here will load page here itself. would prefer redirect.

Select all the anchors in your page and then use setAttribute function to update the target attribute

 let anchors = document.querySelectorAll('a'); for (let i = 0; i < anchors.length; i++) { anchors[i].setAttribute('target', '_blank') }
 <a href="there_links.com" target="_blank">link 1</a> <a href="a.com">link 2</a> <a href="there_links.com">link 3</a>

the above script could be set inside mounted hook in Vue component

You can query <a> that have no target and set it something like:

document.querySelectorAll('a:not([target])').forEach(el => el.target = "_blank")

The critical part is running it only after you have processed the markdown into elements

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM