Calling a function inside an iframe from outside t

2019-02-12 13:15发布

This question already has an answer here:

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?

7条回答
霸刀☆藐视天下
2楼-- · 2019-02-12 13:29

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.

查看更多
Explosion°爆炸
3楼-- · 2019-02-12 13:29

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();

查看更多
Root(大扎)
4楼-- · 2019-02-12 13:31
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.

查看更多
相关推荐>>
5楼-- · 2019-02-12 13:38

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楼-- · 2019-02-12 13:39

This can be done with JavaScript:

window.top.location.href = url;

Works perfectly in all major browsers.

查看更多
够拽才男人
7楼-- · 2019-02-12 13:49

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)

查看更多
登录 后发表回答