A correctly encoded string is decoded when entered in window.location.hash

Purpose: To correctly place the string from the data attribute in window.location.hash .

The code:

 map = {path: $(this).attr('data-path'), rev: $(this).attr('data-rev')}; window.location.hash = getMapParams(map); function getMapParams(map) { s=""; for(key in map) { value=eval("map."+key); if (s.length > 0) { s+="&"; } s+=encodeURIComponent(key)+"="+encodeURIComponent(value); } return s; } 

Problem: Once the data-path attribute contains a space, Firefox cannot properly place the hash. The space will be displayed unencoded, while in other browsers it is correctly encoded as %20 .

Strange quirks: If I debug the code, the line will be indicated in the encoded space.

Research: I found many solutions for reading the hash correctly in firefox. Somehow it works fine with my code.

Question: How to stop Firefox from urldecoding the space (s) in a string placed in window.location.hash

+4
source share
1 answer

Usually I try to avoid window.location.hash due to the fact that it is not homogeneous in different browsers.

So instead of doing the following

 window.location.hash = "some hash value"; 

I would do

 window.location.href = window.location.href.split("#")[0] + "#" + encodeURIComponent("some hash value"); 

Also, although Firefox shows a decoded hash in the address bar (i.e., '' instead of% 20), if you try to copy the address, it is actually encoded. Thus, what is displayed does not match what is in the URI.

As an aside, I always access the hash using the following code

 var hash_val = window.location.href.split("#")[1] || ""; 
+5
source

Source: https://habr.com/ru/post/1403639/


All Articles