Why does history back not work on onclick in Firefox?

后端 未结 4 1720
[愿得一人]
[愿得一人] 2021-02-06 02:50

I don\'t understand why in Firefox, window.history.back() does work on a button:

4条回答
  •  臣服心动
    2021-02-06 03:24

    You are facing this issue (quoted from vikku.info):

    But what had happened when i press the back button after navigating to various pages was i got locked between the last two navigated pages.

    Someone in the comments hit the nail on this issue.

    • When you create the onclick attribute, you are attaching an additional event handler for clicking a link. However, the browser will still handle some native logic, so it will still add the current page to the history;
    • When you pass in specific javascript into the href attribute, you are actually overriding the native logic of the browser, so it won't add the current page to the history;

    SIMPLE, DIRTY SOLUTION

    HTML:

    Back
    

    IMPROVED SOLUTION

    I've also created an example (Plunker example) that makes use of the native preventDefault functionality (MDN on preventDefault). In that case, it is not needed to write javascript in the href attribute. Now, you can support users that are not using javascript by linking to, for example, the homepage. You better also avoid using inline event handlers.

    HTML:

    Back
    

    Javascript:

    var backbutton = document.getElementById("backButton");
    backbutton.onclick = function(e){
      e = e || window.event; // support  for IE8 and lower
      e.preventDefault(); // stop browser from doing native logic
      window.history.back();
    }
    

提交回复
热议问题