Calling a function inside an iframe from outside the iframe [duplicate]

杀马特。学长 韩版系。学妹 提交于 2019-11-30 02:47:32

问题


I have a page with an iframe. Inside that iframe I have a javascript function like this:

function putme() {}

How can I call this function on the main page?


回答1:


window.frames['frameName'].putme();

Do note that this usually only works if the iframe is referring to a page on the same domain. Browsers restrict access to pages within frames that belong to a different domain for security reasons.




回答2:


For even more robustness:

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;
}

and

...
var el = document.getElementById('targetFrame');

var frame_win = getIframeWindow(el);

if (frame_win) {
  frame_win.putme();
  ...
}
...



回答3:


If the iframe is in a different domain than the outer page, with great difficulty, or not at all.

In general, the browser prevents javascript from accessing code from a different domain, but if you control both pages, there are some hacks to make something work. More or less.

For example, you can change the fragment of the URL of the iFrame from the outer one, poll the fragment from inside the iframe and call that function. There is a similar trick with the name of the window.




回答4:


On the frameset, specify a name for your frame and in main page you can access the frame by its given name:

window.[FrameName].putme();




回答5:


You can access the iframe with it's name:

foo.putme();

Functions declared globally inside the iframe page will become members of the window object for that iframe. You can access the window object of the iframe with the iframe's name.

For this to work, your iframe needs to have a name attribute:

<iframe name="foo" ...>

Also, the main page and the iframe page should be from the same domain.




回答6:


Give the frame a name and an id - both identical. window.frameNameOrId_.functionName()

Both frames must be in the same domain (though there are ways around this to limited degree)




回答7:


This can be done with JavaScript:

window.top.location.href = url;

Works perfectly in all major browsers.



来源:https://stackoverflow.com/questions/1663242/calling-a-function-inside-an-iframe-from-outside-the-iframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!