How can I create a function in another frame?

懵懂的女人 提交于 2019-12-25 04:07:39

问题


I have a 3rd party generated frameset (from a help system) and I can add code to the subframe that has my content pages. I cannot modify the other frameset content since it is generated by a build process.

I can have some js code myhandler() on each of my HTML content page that gets loaded into the subframe. This myhandler() is triggered to be called when an action occurs in the top frame.

I would like to create the function in the subframe but have it owned by the parent (top) frame, so that it only gets created once meaning I can test if top.myhandler is already set and if so it just reuses it.

When the subframe is loaded with different content HTML then the myhandler() function that was created in the previous content page is no longer accessible when the parent action triggers the call to it.

Is this possible in javascript for a frame to create a function in another frame? Or is there another solution to this?


回答1:


There is 1 condition for cross-frame javascript: All involved pages (in different frames) need to be on the same domain. If pages are on different domains or subdomains - cross-frame javascript access will be restricted for security purposes.

Lets suppose you have a frameset with 2 pages: index.html and index2.html

If these pages are on the same domain - they will share the same javascript namespace, i.e. all javascript libraries linked to index.html will be accessible from index2.html and versa versa.

If pages are located on different subdomains of the same domain - it is possible to step several levels up. For example:

frame1 contains:    http://myrepo.site.com/index.html
frame2 contains:    http://another.site.com/index2.html

you can set for both (in JavaScript): document.domain = "site.com" After that - javascript code on both pages will start seing each other, same as these pages are on the same domain.



来源:https://stackoverflow.com/questions/7617429/how-can-i-create-a-function-in-another-frame

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