1

For example: I have a main page with an iframe in it and my iframe contains a button. When I press the button inside the iframe some scripts are executed, and the design of iframe is changed. Texts appears and other stuff.

How do I detect when iframe scripts are run? (Or the button was pressed?)

The iframe is from a different domain.

Jon Adams
  • 24,464
  • 18
  • 82
  • 120
Pytagora
  • 77
  • 1
  • 1
  • 7
  • Do you have any control over the other domain... are you able to update anything on it? If not, then @PhonicUK is correct, you will hit [same origin policy restrictions](http://en.wikipedia.org/wiki/Same%5Forigin%5Fpolicy). If you do then it's possible to allow access using CORS for example... see [this answer](http://stackoverflow.com/a/3083131/930393) for more details – freefaller Aug 24 '12 at 09:32
  • I don't have any control in the iframe code... I am thinking if I can detect when it is clicked... Is this possibile? – Pytagora Aug 24 '12 at 09:33
  • 1
    No, if you have no control over the source of the iFrame, then you are completely out of luck... you cannot access **anything** within the iframe (DOM, code, events, etc) and for good security reasons – freefaller Aug 24 '12 at 09:34

4 Answers4

3

If the contents of the iframe come from a different domain than the outside page, then you can't - the browser deliberately stops you from being able to tell much about what is going on inside the iframe. What you can do though is grab the URL the frame is pointing to if it changes.

If it's running in the same domain, you can just access the elements inside the iframe pretty much the same way as you would normally via the document property of the iframe

PhonicUK
  • 13,486
  • 4
  • 43
  • 62
0

If the main page and the iframe are on the same domain, you can make the javascript in the iframe call a function or access the elements of the parent frame.

So at the end of the script in the iframe you can do

parent.script_is_finished();
tomsv
  • 7,207
  • 6
  • 55
  • 88
0

If you have control over the script in the iframe, you could use window.postMessage to communicate with your main page, even if they are in different domains.

Support for this is limited to FF3+, IE8+, Chrome, Safari(5?), Opera10+

Here's a demo on html5demos.

Community
  • 1
  • 1
RYFN
  • 2,939
  • 1
  • 29
  • 40
0

As an update to the fact that the iframe is from a different domain:

Short answer: No. You can't detect clicks within an iframe from another domain.

Longer but still short answer: The reason you can't is the same reason you can change the contents of the iframe -- it'd be a security risk unless the iframe is on the same domain. You simply can't track user activity within an iframe sourced from a different domain.

Sorry, but I hope that helped!

Chris
  • 26,544
  • 5
  • 58
  • 71
  • @Pytagora We **might** be of more help if you tell us what you're trying to achieve in the big picture. – Chris Aug 24 '12 at 09:43