0

Im scraping a website and Im trying to redirect to another website if people click on a link so I injected some javascript:

$('a').on('click', function() {

for (var ls = document.links, numLinks = ls.length, i=0; i<numLinks; i++){
    ls[i].href= 'http://mywebsite.com/test.php?url=' + this;
}

});

It works, but it only works on actual links <a href..>. Sometimes a click on an element will act as a link do to some javascript, I also would like to capture that 'event'. It has me thinking about XMLHttpRequest if I Im not mistaken the browser has a built in object called XMLHttp object, which one could use to intercept ajax calls:

(function(open) {
  XMLHttpRequest.prototype.open = function(method, url, async) {

//do something...

So my question is: Does anything similar exist for listening and altering outgoing URL's?

Youss
  • 4,196
  • 12
  • 55
  • 109

1 Answers1

2

Just so I'm clear on this, whenever somebody clicks on a link, you want to figure out what that URL is, alter it, then redirect the user to your own URL?

$('a').on('click', function(event){
  event.preventDefault();
  var url = $(this).attr('href');
});

preventDefault() will stop the page from redirecting.

At this point, url will be the URL string, and you can do whatever you want to it. To redirect the user, either use window.location.href or window.location.replace.

JSfiddle here http://jsfiddle.net/JQ5qC/

bioball
  • 1,339
  • 1
  • 12
  • 23
  • What if some javascript is generating the URL like so: http://jsfiddle.net/JQ5qC/1/ – Youss Feb 11 '14 at 19:08
  • Not quite sure what you mean. When is JavaScipt generating a URL? In your example, you're simply redirecting the page to CNET on click, anywhere in the HTML page. – bioball Feb 11 '14 at 19:14
  • 'simply redirecting the page' Yes by javascript which holds the 'URL'. So the question is; how do I intercept this URL and change it before leaving for its destination? – Youss Feb 11 '14 at 19:16
  • Do you want to intercept the page redirect when somebody clicks on a hyperlink, or intercept it at all times when the URL changes? – bioball Feb 11 '14 at 19:29
  • I think intercept it at all times when the URL changes. Which obviously includes 'intercept the page redirect when somebody clicks on a hyperlink' – Youss Feb 11 '14 at 19:33
  • 1
    I haven't done anything with this personally, but you should look into window.onbeforeunload http://stackoverflow.com/questions/1704533/intercept-page-exit-event – bioball Feb 11 '14 at 21:27