在子iframe中将window.location用作相对网址 [英] Using relative url for window.location in child iframe
问题描述
我在处理与iframe相关的问题时遇到了麻烦.
I'm having trouble with an iframe-related issue.
我有一个带iframe(子级)的文档(父级).如果父级文档在子级中调用一个函数,该函数使用window.location将子级url更改为相对URL,则该URL相对于父级文档.让我说明一下.
I have a document (parent) with an iframe (child). If the parent document calls a function in the child which changes the childs url using window.location to a relative url, that url becomes relative to the parent document. Let me illustrate.
父文档:/test/parent.html
Parent document: /test/parent.html
子文档:/projects/child.html
Child document: /projects/child.html
子代码:
function moveOn(){
window.location.href = "newPage.html";
}
父代码:
childDocument.contentWindow.moveOn();
结果: 子文档尝试访问/test/newPage.html 而不是/projects/newPage.html
Result: Child document tries to access /test/newPage.html instead of /projects/newPage.html
有什么办法可以解决这个问题吗?我处于无法仅在父文档中更改子文档代码的情况下.
Is there any way of fixing this from the parent? I am in a situation where I can't make changes in the child document code, only in the parent.
谢谢, 尼克
这是实际的代码
在父级(/testr/testr.html):
In parent (/testr/testr.html):
testr.appHolder = $("childIframe");
testr.appHolder.src = "../projects/test.html";
testr.functionName = "moveOn";
testr.appHolder.contentWindow[testr.functionName]();
在子(/projects/test.html)中:
In child (/projects/test.html):
function moveOn(){
window.location.href = "newPage.html";
}
这是实际的代码
This is the actual code
在父级(/testr/testr.html)中:
In parent (/testr/testr.html):
testr.appHolder = $("childIframe");
testr.appHolder.src = "../projects/test.html";
testr.functionName = "moveOn";
testr.appHolder.contentWindow[testr.functionName]();
在子项(/projects/test.html)中:
In child (/projects/test.html):
function moveOn(){
window.location.href = "newPage.html";
}
推荐答案
最后,是完整的解决方案!
childDocument.contentWindow.setTimeout( childDocument.contentWindow.moveOn, 0 );
这要求子文档在零毫秒内执行给定功能(moveOn
),并且在子上下文中执行,即使在Internet Exploder中也是如此.
This asks the child document to execute the given function (moveOn
) in zero milliseconds, and it is executed in the context of the child, even in Internet Exploder.
Booyah.
这篇关于在子iframe中将window.location用作相对网址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!