Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Change All Links with javascript

I want to change all links of my site. Suppose a link given by .Example http://www.google.com/ changes to http://www.mysite.com/?redirect=http://www.google.com/

i have my own redirector just i need to change the links via javascript for all url

like image 906
user1809599 Avatar asked Nov 08 '12 14:11

user1809599


People also ask

How do I change a link in JavaScript?

You can also use the location. replace method to perform JavaScript redirects. The location. replace method allows you to replace the current URL with a different URL to perform redirection.

What is the correct way of changing the URL of a page using JavaScript?

window. location. replace() replaces the current URL with a new one, whilst overwriting the old URL's entry in the history.

How do I modify a link?

Change an existing hyperlinkRight-click anywhere on the link and, on the shortcut menu, click Edit Hyperlink. In the Edit Hyperlink dialog, select the text in the Text to display box. Type the text you want to use for the link, and then click OK.

Can we use HREF in JavaScript?

In JavaScript, you can call a function or snippet of JavaScript code through the HREF tag of a link. This can be useful because it means that the given JavaScript code is going to automatically run for someone clicking on the link. HREF refers to the “HREF” attribute within an A LINK tag (hyperlink in HTML).


2 Answers

Just another version with some checks for local links 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);
    }
});
like image 165
Andreas Avatar answered Oct 06 '22 07:10

Andreas


var anchors = document.getElementsByTagName("a");

for (var i = 0; i < anchors.length; i++) {
    anchors[i].href = "http://www.mysite.com/?redirect=" + anchors[i].href
}

You can then make the code run on page-load by wrapping it in a function linked to window.onload event:

window.onload = function() {
       /* onload code */
}
like image 37
Beardy Avatar answered Oct 06 '22 09:10

Beardy