简体   繁体   中英

How to redirect a page for external links except social links


I have a Blogger blog and i want to keep track of exxternal links by making a redirect page with javascript for all links except internal links and social links.
I know how to do it like this:

window.onload = function(){
document.getElementById("aLinkId").addEventListener("click", function(e){
e.preventDefault();
// Here we redirect to the wanted page, with the extra parameter, with the original external URL
location.href = "REDIRECT-PAGE-URL?redirect=" + document.getElementById("aLinkId").href; 
}); };

But that doesn't work in blogger links don't have id, i'd have to put it for every link.
but for the redirect page, I'm stuck.

You can get all the links using querySelectorAll and then loop through each link and add an event listener on them. This way does not depend on each link having a unique ID.

 window.onload = function() { let links = document.querySelectorAll("a"); for (var i = 0; i < links.length; i++) { links[i].addEventListener("click", function(e) { e.preventDefault(); let href = this.href console.log(href); //location.href = "REDIRECT-PAGE-URL?redirect=" + href; }); } }; 
 <a href="url1" target="blank">link1</a> <a href="url2" target="blank">link2</a> <a href="url3" target="blank">link3</a> <a href="url4" target="blank">link4</a> 

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