我有一个带有iframe的页面。在iframe里面我有一个这样的javascript函数:从iframe外部调用iframe中的函数
function putme() {}
如何在主页面上调用此函数?
我有一个带有iframe的页面。在iframe里面我有一个这样的javascript函数:从iframe外部调用iframe中的函数
function putme() {}
如何在主页面上调用此函数?
如果iframe与外部页面位于不同的域中,很难或根本不存在。
一般来说,浏览器可以防止javascript访问来自不同域的代码,但是如果你控制了这两个页面,就会有一些黑客让某些东西有用。或多或少。
例如,您可以从外部URL更改iFrame的URL片段,轮询iframe中的片段并调用该函数。有一个与窗口名称类似的技巧。
你可以用它的名称来访问的iframe:全局声明的iframe页面内将成为该iframe窗口对象的成员
foo.putme();
功能。您可以使用iframe的名称访问iframe的窗口对象。
对于这个工作,你的iframe需要有一个name属性:
<iframe name="foo" ...>
此外,主面和iframe页面应该是来自同一个域。
给框架一个名称和一个id - 两个相同。 window.frameNameOrId_.functionName()
两个框架必须是同一个域(虽然这种情况有解决办法有限度)
在框架,为你的框架,并在主要页面中指定的名称你可以按给定名称访问该框架:
window。[FrameName] .putme();
window.frames['frameName'].putme();
请注意,这通常只适用于iframe指的是同一个域上的页面。出于安全原因,浏览器限制对属于不同域的帧内的页面的访问。
为了获得更大的鲁棒性:完美在所有主要浏览器
window.top.location.href = url;
作品:
function getIframeWindow(iframe_object) {
var doc;
if (iframe_object.contentWindow) {
return iframe_object.contentWindow;
}
if (iframe_object.window) {
return iframe_object.window;
}
if (!doc && iframe_object.contentDocument) {
doc = iframe_object.contentDocument;
}
if (!doc && iframe_object.document) {
doc = iframe_object.document;
}
if (doc && doc.defaultView) {
return doc.defaultView;
}
if (doc && doc.parentWindow) {
return doc.parentWindow;
}
return undefined;
}
和
...
var el = document.getElementById('targetFrame');
getIframeWindow(el).putme();
...
这可以用JavaScript实现。
我在firebug中调试它,它说:m.contentwindow.putmap不是一个函数 – jamal 2009-11-02 19:55:05