【问题标题】:Reading Parent's URL阅读家长的网址
【发布时间】:2011-11-20 20:56:30
【问题描述】:

我有一个运行一些 Javascript 的 iFrame,我希望 iFrame 根据加载到的页面表现出不同的行为。我发现这段代码运行良好,但它显示的是 iFrame 的 url 而不是父级。

 var Page1 = "page1.html";
 var Page2 = "page2.html";
 var thisUrl = decodeURI(window.location);
 var urlChunks = thisUrl.split("/");

for (var chunk in urlChunks) {
alert('chunk: ' + chunk);
alert('urlChunks[chunk]: ' + urlChunks[chunk]);

if (urlChunks[chunk] == Page1) {
alert('inside index.html');

}

else if (urlChunks[chunk] == Page2) {

}

else
{

}

}

我可以改变什么

decodeURI(window.location);

to 为了让它从父级读取。

【问题讨论】:

  • 如果你想要父 url,这里已经回答了:stackoverflow.com/questions/115526/…
  • 这似乎对我不起作用 =S 它返回未定义而不是父 url。我的文件结构会影响这个吗?
  • @eddy147 抱歉没有标记你的名字

标签: javascript jquery html iframe


【解决方案1】:
window.parent.location

请记住,JavaScript 具有同源限制,因此当父文档是不同的来源(例如域)时,您很可能会收到拒绝访问的异常。

【讨论】:

  • 代码似乎没有运行 =/.我的父母在 Website/profile/Page1.html 但我的框架在 Website/frames/child.html 可能会导致访问被拒绝异常
  • 不,在这种情况下它不应该触发任何异常。我的信息太少,无法告诉您为什么我的代码不适合您。它应该。 parent 属性是获取框架文档的父级的正确方法。
  • 进一步,它是 window.parent.location.url 否则你可能只是返回位置对象。
  • @Matt:不是真的。 url 不是 window.location 的属性。文档具有 URL 属性。如果您需要将 URL 作为字符串,则使用 parent.location.href,但如果您在位置对象上使用 decodeURI,它将被转换为字符串。
  • @Rafael 我的错误。 window.parent.location.href
猜你喜欢
  • 2021-09-15
  • 2012-11-06
  • 1970-01-01
  • 1970-01-01
  • 2011-07-18
  • 1970-01-01
  • 2014-11-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多