“[removed].hash = location.hash” does not work in Webkit (Safari & Chrome)

前端 未结 5 877
一向
一向 2021-01-12 06:14

I can\'t get window.location.hash = location.hash to work in Safari.

I\'m using javascript to wrap the contents of my page with a scrollable DIV, placed

相关标签:
5条回答
  • 2021-01-12 06:39

    Webkit has two oddities that prevent window.location.hash = location.hash from working normally.

    1. Webkit responds to window.location.href instead of window.location.hash (like all the other browsers do). Curiously, webkit can still read the URL's hash tag using location.hash
    2. Webkit has a documented bug where the href location has to be set to the same location twice before the browser will go to the new location. Bug report here.

    This code solved my problem: (using jQuery).

    $(document).ready(function() {
        gotoHASH()
    };
    
    function gotoHASH() {
        if (location.hash) {
            if ( $.browser.webkit == false ) {
                window.location.hash = location.hash;
            } else {
                window.location.href = location.hash;
            }
        }
    };
    
    0 讨论(0)
  • 2021-01-12 06:46

    I ended up with

    window.location.hash = "";
    window.location.hash = "myanchor";
    

    This worked fine in all desktop browsers I tested in and on iOS and Android chrome.

    0 讨论(0)
  • 2021-01-12 06:48
    go_hash('#home')
    

    The function...

    function go_hash(hash) {
      console.log('go_hash: ' + hash)
      if(hash.indexOf('#') == -1)
        hash = '#' + hash
      if(document.location.hash) {
        document.location.hash = hash
        return
      }
      if(window.location.hash) {
        window.location.hash = hash
        return
      }
      if(document.location.href) {
        document.location.href = hash
        return
      }
      window.location.href = hash
    }
    
    0 讨论(0)
  • 2021-01-12 06:49

    Before JavaScript changes the orginal hash location, get the scroll position using

    var st = $(window).scrollTop().
    

    When you want to restore the scroll location, use

    $(window).scrollTop(st);
    
    0 讨论(0)
  • 2021-01-12 06:56

    Set location.hash to something else first and immediately set it back.

    var t = window.location.hash;
    window.location.hash = "non-existant-id";
    window.location.hash = t;
    
    0 讨论(0)
提交回复
热议问题