0

Possible Duplicate:
Can javascript access iframe elements from the parent page?

I have an iframe in my document, and I want to get (and change) some attributes in it with JQuery. This is the code:

var iframe = $('iframe');

        $("#id").click(function() {
            var btn = iframe.contents().find('a[href*="script.php"]'); 
            alert(btn);
            for (var i=0, attrs=btn.attributes, l=attrs.length; i<l; i++){
                alert(attrs.item(i).nodeName);
            }
         });

The first alert says "[object Object]", then I'm getting errors:

Unsafe JavaScript attempt to access frame with URL http://somedomain.ru/somescript.php from frame with URL http://domain.wia-games.net/. Domains, protocols and ports must match.

and

Uncaught TypeError: Cannot read property 'length' of undefined

How should I solve the problem?

UPD. console.log(btn):

[prevObject: st.fn.st.init[0], context: document, selector: "a[href*="script.php"]", jquery: "1.9.0", constructor: function…] context: #document length: 0 prevObject: st.fn.st.init[0] selector: "a[href*="script.php"]" proto: Object[0]

Community
  • 1
  • 1
artem
  • 16,382
  • 34
  • 113
  • 189

2 Answers2

2

This is a constraint implemented on browsers for security reasons: Same origin policy

Safe Workarounds exist:

Nabil Kadimi
  • 10,078
  • 2
  • 51
  • 58
1

Most Browsers as a security feature prohibit Cross Site Scripting: http://en.wikipedia.org/wiki/Cross-site_scripting

That means the two Objects must have the same source domain.

As a workaround you might want to query the foreign page on the server-side (e.g. with php)

Ian
  • 50,146
  • 13
  • 101
  • 111
Edmund Moshammer
  • 688
  • 7
  • 19