从 iframe 中获取 URL 并更新浏览器 URL 中的哈希值

5

我尝试了不同的方法,但都没有奏效。基本上,我需要从iframe中获取当前位置/ url,获取我想要的部分并将其返回到url的哈希值中。在JavaScript中,我该怎么做呢?

1个回答

6
选择正确的iframe元素,提取出src属性,进行必要的处理后,将src赋值给window.location.hash。
var iframe = $('iframe');
var src    = iframe.attr('src');
window.location.hash = src;

编辑

如果您想从iframe中获取动态位置,则必须访问contentWindow属性:

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

window.location.hash = url;

获取contentWindow属性的有趣阅读:

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


3
当用户在iframe内浏览/跳转到不同页面时,src并没有更新,这使得它失去了作用。还有其他的解决方案吗? - Adam
2
+1 很好的回答,但遗憾的是我认为仍然存在跨域问题。 - Mottie

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接