1

By pressing the alt-key and click on a url, chrome makes a download. This because of the browsers default alt+click action. How can I prevent that? It should exchange the url.

The code works with other keys (for example x == 88), where the browser has no default actions. But how with the alt-key?

 //ALT-key recognition
    document.onkeydown=function(){
        var keyCode = event.keyCode;
  if(keyCode == 18) //alt-key
        {
            console.log(keyCode);
   
     document.getElementById("hist").setAttribute ('href', "history_by-date.php?wdate=all");
        }
    }
 <div id="history">                                    
     <a href="history_by-date.php?wdate=2018&until=2017" id="hist"  target="_self" class="a2">should be just a link - not a download (when alt is pressed)</a>
     </div><!-- end history -->

Another user here skyline3000 has an interesting article with prevent code, but I bring it not to work. Thanks for any help.

evt.preventDefault();
evt.stopPropagation();
return false;
doschni
  • 43
  • 8

2 Answers2

2

Rather than listening to a keypress I think you need to listen to the link click events and check the event.altKey property. I'm not 100% if this is bulletproof vs alt-click download, but it seems to work. Note, using this.click() to invoke the link will only work if it's a normal href, no javascript or click events. There are other more complex ways to do that part otherwise.

document.querySelectorAll('a').forEach(a => {
  a.addEventListener('click', function (e) {
    if (e.altKey) {
      e.preventDefault(); // no download
      this.href = 'history_by-date.php?watchdate=all';
      this.click(); // fake a normal click
    }
  });
});
<a href='http://example.com'>alt-click me</a>
James
  • 20,957
  • 5
  • 26
  • 41
  • Thanks for new viewpoint. To href I added the id="hist" and in js I exchanged the this.Click(); with document.getElementById("hist").setAttribute ('href', "history_by-date.php?watchdate=all"); – doschni Nov 30 '18 at 21:20
  • In JsFiddle it's working partwise, but the new url is showed only after the click. On my Website it's not reacting anywise, unfortunately. It's also downloading. But I will deepen me more in your viewpoint. – doschni Nov 30 '18 at 21:30
  • No you can't just set the href attribute in that function, you have to cause the browser to visit the url too, either by using the click() trick I showed or something like `window.location.href = 'history_by-date.php?watchdate=all'` - Try the change I made. – James Nov 30 '18 at 21:38
0

What you are asking is to change the users' browser's default actions. This is not possible. A default action from the browser wont run in the HTML DOM, thus not being detectable.

  • Confirming this seems to be the case; `e.preventDefault()` did not stop the downloading of the page when alt+clicking a link in Chrome. – Kalnode Feb 10 '23 at 00:22