javascript location.hash refreshing in IE

后端 未结 9 1245
既然无缘
既然无缘 2020-11-28 06:03

I need to modify the hash, remove it after certain processing takes place so that if the user refreshes they do not cause the process to run again.

This works fine

9条回答
  •  臣服心动
    2020-11-28 06:23

    Here is a cross-browser solutions. Works in IE, Chrome, Safari, and FF (tried with latest versions).

    var pos = location.href.indexOf('c=');
    location = (pos < 0 ?
                        location + (location.href.indexOf('?') < 0 ? '?' : '&')
                        : location.href.substring(0, pos))
               + 'c=' + Math.floor(Math.random()*11) + '#' + comment_id ;
    

    Basically, I leverage query ("?") string to trigger the page reload with hash. What the first line does is it checkes whether there is our "golden" query string (I use "c" variable which stands for "comment"). If there is,

    1. the new URL will have everything before that "c=";
    2. then adds our golden "c=" + a random number between 0 and 10 + "#" + my comment id to which the browser needs to jump when reloaded.

    If there is no,

    1. the new URL will have everything old URL used to have;
    2. if the old URL already contains some other query string (something after "?"), add a query append operator "&";
    3. if no "?", then add it;
    4. then goes the above mentioned "golden" query.

    The reason I add a random number after "?" is that after the first reload there is something like "?#comment-10". In this case, the next change to the URL will not reload the page, since browser understands it as an anchor jump instruction.

    To force reload, we need to add some random thing to the query so that the new URL is different from the previous.

    This solution will work on all browsers and will make sure the reload doesn't break the existing query. The only note is to make sure your "golden" query variable name is unique.

    Hope this helps.

提交回复
热议问题