Jquery doesn't return hash url

I am trying to get a hash value for the current page without success. I am targeting a page with a link, for example:

http://www.mydomain.com/test.html#hash 

My jquery for test.html is as follows:

 $(document).ready(function() { if (window.location.hash){ console.log ("FOUND HASH"); }else{ console.log ("HASH NOT FOUND"); } }); 

No matter what I do, I never get a hash value; it's always empty. "However, when I break the code with Firebug and look at the DOM, I clearly see that the hash value is set correctly under window.location.hash .

What am I doing wrong?

Thanks in advance for your help.

ANSWER TO ANSWER: It turns out that masking my web address creates a frame wrapper around the entire page, in this case with different ports. The hash was preserved by the parent frame, but was lost for the child and is not accessible by jquery code. Using a direct non-loaded address led to the correct behavior.

+4
source share
3 answers

The hash is at your top frame / window level. Your javascript is not in this top window. So, when you window.location.hash to window.location.hash , you are viewing the URL of your frame, not the top-level window that appears in the browser bar.

And since your top-level window and your internal frame are not the same domain / port, you will not be able to communicate between them. Make them the same domain, and you can get window.location.hash from the top-level window (which appears in the browser URL bar).

If your domains are the same, so you do not run security restrictions of the same origin , then you can get a hash on top of the URL with this:

 window.top.location.hash 

FYI, the top-level window has only this in it (this is not where your javascript is):

 <HTML><HEAD> <META NAME="description" CONTENT="robtune.com"> <META NAME="keywords" CONTENT=""> </HEAD> <FRAMESET border=0 rows="100%,*" frameborder="no" marginleft=0 margintop=0 marginright=0 marginbottom=0> <frame src="http://www17.robtune.com:8017/test.html" scrolling=auto frameborder="no" border=0 noresize> <frame topmargin="0" marginwidth=0 scrolling=no marginheight=0 frameborder="no" border=0 noresize> </FRAMESET> </HTML> 
+1
source

You can try the following:

 window.parent.location.hash 
+1
source

Are you using IFRAME on the page and trying to get a hash?

and please give us a demo url to help you respond quickly. Updated:

You can use:

window.parent.location.hash to get the hash value.

0
source

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


All Articles