I would like to manipulate the html inside an iframe using jquery

[亡魂溺海] 提交于 2021-01-27 13:22:26

问题


I thought I'd be able to do this by setting the context of the jQuery function to be the document of the iframe, something like:

$(function(){//document ready
$('some selector', frames['nameOfMyIframe'].document).doStuff()
});

However this doesn't seem to work. A bit of inspection shows me that the variables in frames['nameOfMyIframe'] are undefined unless I wait a while for the iframe to load. However, when the iframe loads the variables are not accessible (I get permission denied type errors).

Does anyone know of way to work around this?


回答1:


The only "workaround", if you can't make the other site include the relevant CORS headers, would be to fetch the iframe content server side and serve it as coming from your own domain.

The reason there isn't simpler workaround is due to why there is this same origin policy : to protect users.

you can not perform any access with cross domain iframe




回答2:


As stated above, your issue is what is known as the "Same Origin Policy" which essentially is a scope-related problem. Communication between inherently separate html documents is not legal. There are, however, workarounds for the several occasions where iframe's residing on the same page can communicate with one another using the help of a third-party intermediary, check out this amazing solution for an example:

Resizing an iframe based on content



来源:https://stackoverflow.com/questions/19225590/i-would-like-to-manipulate-the-html-inside-an-iframe-using-jquery

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