Inline script: Detect if request comes from inside an iframe. Any idea?

Hello,

I am writing a inline script for a university project, which should add to every website html data, like a overlaying advertisement. With injecting javascript there are problems with many websites, when they also use javascript.
Then the injected content is in some cases not displayed like it should be or it is displayed not at all.

My actual idea is, that I respond for every request, which don’t contains a key appended to the URL, with a direct response from the mitmproxy containing html data (e.g. with the advertisement). This html data includes a iframe.
The inline script replaces the iframe src with the requested URL and appends a keystring through that the inline script can detect, that the (next) request comes from inside of the iframe and because of that don’t changes the response.

Browser             Mitmproxy              requested Server
   | request to             |                       |
   | e.g. mitm.it           |                       |
   |----------------------->|                       |
   |                        |                       |
   |          No keystring  |                       |
   |    send own html data  |                       |
   |     containing iframe  |                       |
   | with src="mitm.it/keystring.html"              |
   |<-----------------------|                       |
   |                        |                       |
   | request: mitm.it/keystring.html                |
   |----------------------->|                       |
   |                        | request: mitm.it      |
   |                        |---------------------->|
   |                        |                       |
   |                        |<----------------------|
   |<-----------------------|                       |
   |                        |                       |
######################################################
   |requests additional data|                       |
   |----------------------->|                       |
   |                        |detect by referer      |
   |                        |if referer conatins kexstring
   |                        | forward request       |
   |                        |---------------------->|
   |<-----------------------|<----------------------|
   |                        |                       |
   ---------------------------------------------------
   |                        |else send own html     |
   |<-----------------------|  data directly        |
   |                        |                       |

Does someone know a better way how to detect it?
Requests for additional data should always be passed through the mitmproxy, to the requested server.
The big problem is, that not everytime the referer contains the keystring, when additional data is requested.

I would be happy if someone has a cool idea.