Error trying to access a iframe in JavaScript

为君一笑 提交于 2020-01-12 08:58:32

问题


I'm trying to call the function SC.Widget from this little API: http://developers.soundcloud.com/docs/api/html5-widget, but I receive this error message in the Chrome inspector and I am stuck there.

Unsafe JavaScript attempt to access frame with URL file://localhost/Users/maxwell/Desktop/test/test.html from frame withURL

http://w.soundcloud.com/player/?url=http%3A%2F%2Fapi.soundcloud.com%2Ftracks%2F67825032&auto_play=false&show_artwork=true&color=ff7700.

The frame requesting access has a protocol of 'http', the frame being accessed has a protocol of 'file'. Protocols must match.

<body>
    <iframe id="soundcloud" width="100%" height="166" scrolling="no" frameborder="no"
    src="http://w.soundcloud.com/player/?url=http%3A%2F%2Fapi.soundcloud.com%2Ftracks%2F67825032&amp;auto_play=false&amp;show_artwork=true&amp;color=ff7700"></iframe>
    <script>
        Soundcloud();
    </script>
</body>


function Soundcloud() {
    var widget1 = SC.Widget(iframeElement.soundcloud);
    alert("widget1");
}

I know it's doing this for security reasons, but how do I modify the SoundCloud widget if I can't access the frame?

Thank you for helping!


回答1:


When accessing an iframe with JavaScript or making any JSON AJAX requests, you can only get access or a response when they are on the same domain. Otherwise, the server must explicitly set:

Access-Control-Allow-Origin: *

in the headers. You can also provide a comma-separated list of allowed domains instead of *.

So you must test this in a development environment where the web page and data source are on the same domain, such as localhost, otherwise there isn't really anything else you can do unless you start-up chrome with --disable-web-security




回答2:


You could add this to your iframe

sandbox="allow-same-origin allow-scripts"

not supported in opera though - new item from w3schools. It will take care of the error, but it will break the player.



来源:https://stackoverflow.com/questions/13446106/error-trying-to-access-a-iframe-in-javascript

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