且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

javascript、iframe、安全性-尝试从父窗口访问 js 函数时权限被拒绝

更新时间:2022-11-25 14:33:15

默认情况下禁止访问来自其他域的页面,因为浏览器使用 同源策略.有几种解决方法,例如使用 location.hash 或 window.name 在框架之间进行通信.HTML5 中最新和标准化的是 postMessage-interface.有跨浏览器解决方案的库http://easyxdm.net/wp/.

Good day to all.

I have a page that includes an iframe. In that iframe I have a script with function called test(). I need to access the function from the parent window. After asking around I got to this solution:

<div onclick="document.getElementById('targetFrame').contentWindow.teste();">Test</div>

On click the test function should be run. The problem is that I get " Permission denied to access property test" error.

It looked like a permission error to me so I changed the file loaded in iframe permissions to 777, but without any result.

Note: The file loaded in iframe is not on the same domain.

It's prohibited to access pages from other domains by default, because browsers use same origin policy. There are several workaround like using location.hash or window.name to communicate between frames. The most recent and standardized in HTML5 is postMessage-interface. There is library for cross-browser solution http://easyxdm.net/wp/.