从iframe获取网址并在浏览器网址中更新哈希

Ada*_*dam 5 javascript url hash iframe jquery

我尝试了一些不同的东西,但没有真正起作用,基本上我需要从iframe获取当前位置/网址,获取我想要的部分并将其返回到网址中的哈希值.我怎么能用javascript做到这一点?

Jur*_*nka 6

选择正确的iframe元素,拉出src属性,做你的东西,将src分配给window.location.hash

var iframe = $('iframe');
var src    = iframe.attr('src');
window.location.hash = src;
Run Code Online (Sandbox Code Playgroud)

编辑

如果您想获得动态位置,iframe您必须访问contentWindow属性:

var iframe     = $('iframe');
var contentWnd = iframe.attr('contentWindow');
var url = contentWnd.window.location.href;

window.location.hash = url;
Run Code Online (Sandbox Code Playgroud)

获取contentWindow属性的有趣读物:

http://www.bennadel.com/blog/1592-Getting-IFRAME-Window-And-Then-Document-References-With-contentWindow.htm

  • 当用户浏览/转到iframe内的不同页面时,src不会更新,因此它无法实现目的.还有其他方法吗? (3认同)
  • +1很好的答案,但遗憾的是我认为仍存在跨域问题. (2认同)