The scenario is a lot of html files with a lot more of links between them. When I call the first one of them (it would be the index), the link pass several parameters through the URL (we could call them preferences).
Now I want that, when clicking any of the several links of the page, those parameters would be added. So the problem would be similar to this other ( How to add parameters to a URL that already contains other parameters and maybe an anchor) but doing it just after clicking the link.
I know that one solution could be changing the onclick event on each link, but as there may be thousands of them, without a regular url format... I'm looking for a solution that could be on the script at the head; perhaps something relative to onbeforeunload event.
Anyway I couldn't find how to do it. Any ideas?
This will append a string to anything containing an href-attribute when being clicked:
window.addEventListener("click", function(e) {
var href = e.target.getAttribute("href");
if(href) {
location.href = href + "?q=stackoverflow";
e.preventDefault();
}
});
Example here: http://jsfiddle.net/E5Q7P/
Won't work in < IE9
Instead of changing the onclick-attribute of each link, or using the onbeforeunload-event, I guess one way would be to attach a clickevent-listener to all anchor-elements when the page loads. The callback could then intercept the browsers default behavior to follow the link. You could then get the src
attribute of the a-element that was just clicked, add the desired preferences to the URL and then send the user to the proper location (including preferences) by setting window.location.href
to the proper URL.
There is a great aricle on MDN about event-listeners, that I believe would be helpful to you. Note specially the section about older versions of IE
A very crude example of what it could look like:
function callback(e){
// Get the src of the clicked a-element
var src = this.src;
// Add preferences to the url, this need
// improvement depending on your needs
src += "?somesetting=foo";
// Send user to the url with preferences
window.location.href = src;
}
// Get all anchors on page
var anchors = document.getElementsByTagName("a");
// Loop over the elements and attach listener
for(i=0 ; i < anchors.length ; i++){
// Extend with support for older IE if needed
anchors[i].addEventListener("click", callback, false});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With