How to make an HTML back link?

后端 未结 12 833
臣服心动
臣服心动 2020-12-12 08:32
12条回答
  •  旧时难觅i
    2020-12-12 09:20

    This solution gives you the best of both worlds

    • Users get to hover over the link to see the URL
    • Users don't end up with a corrupted back-stack

    More details in the code comments below.

    var element = document.getElementById('back-link');
    
    // Provide a standard href to facilitate standard browser features such as 
    //  - Hover to see link
    //  - Right click and copy link
    //  - Right click and open in new tab
    element.setAttribute('href', document.referrer);
    
    // We can't let the browser use the above href for navigation. If it does, 
    // the browser will think that it is a regular link, and place the current 
    // page on the browser history, so that if the user clicks "back" again,
    // it'll actually return to this page. We need to perform a native back to
    // integrate properly into the browser's history behavior
    element.onclick = function() {
      history.back();
      return false;
    }
    back

提交回复
热议问题