How to change all links using javascript

I want to change all the links on my site. Suppose the link is given. The example http://www.google.com/ changes to http://www.mysite.com/?redirect=http://www.google.com/

I have my own redirector, I just need to change the links via javascript for all URLs

+4
source share
4 answers
var anchors = document.getElementsByTagName("a"); for (var i = 0; i < anchors.length; i++) { anchors[i].href = "http://www.mysite.com/?redirect=" + anchors[i].href } 

Then you can make the code run on the loading page by wrapping it in the function associated with the window.onload event:

 window.onload = function() { /* onload code */ } 
+12
source

If you use javascript without a border, you can use the following lines:

 var links, i, le; links = document.getElementsByTagName('a'); for (i = 0, le = links.length; i < le; i++) { links[i].href = "http://www.mysite.com/?redirect=" + encodeURIComponent(links[i].href); } 
+2
source
 $('a').each(function(i, e) { var current = $(this); current.attr('href', 'http://www.mysite.com/?redirect=' + encodeURIComponent(current.attr('href'))) }); 
0
source

Another version with some local link checks and .forEach()

 var links = [].slice.apply(document.getElementsByTagName("a")); links.forEach(function(link) { var href = link.href; if (href.length && href.substring(0, 1) !== "#" && href.substring(0, 1) !== "/") { link.href = "http://www.mysite.com/?redirect=" + encodeURIComponent(link.href); console.log(link.href); } }); 
0
source

Source: https://habr.com/ru/post/1444823/


All Articles