Can i build a API that would let me interact with content inside a iframe?

130 Views Asked by At

I am working on a project where i want to populate web pages in a iframe but due to the CORS i am not able to interact with the content inside the iframe from my app, but people who will display their webpages inside my app can install a code or something on their web page, i tried postMessage but seems like its easy to exploit if someone wants to.

I was wondering if i could develop something sort of a API that can be placed on the users web page and only gets activated when someone visits it from my app and lets the user interact with the web page inside the iframe with custom events ?

We use react js as frontend.

is something of this sorts possible ? if yes how ? how does google analytics tracking code works i believe it too uses postMessage.

Your help is appreciated. Happy to sponsor a coffee if you could help me.

1

There are 1 best solutions below

1
On

I had a very similar problem, the webpage was mine and the iframe content had a script tag that was mine. Here is how you can communicate both ways: iframe to parent, as well as parent to iframe.

This code acts as a kind of listener that listens for messages from other windows. If you want bidirectional communication, you need it on both pages, your client's as well as your own (embedded page as well as embedding page):

window.onmessage = function(e) {
  // this get's triggered when other window sends a message 
  if (e.data == "<some_identifier>") {
    // with e.data you can send an identifier 
    // and then you put the code that should be executed in here (on your page)
  } else if (e.data == "<some_other_identifier>") {
    // other action to do
  }
};

And you send these messages from the embedded iframe website with the postMessage function like this for posting to the parent window (embedding window)

window.top.postMessage("<some_identifier>", "*");

For the other way around, you embed the page like this, the name has to be unique

<iframe src="<your-embedded-url>" name="<some-id>"/>

And then you can send a post with this:

let target = window.frames.<some-id>;
target.postMessage("<some_identifier>", "*");

The asterisk in postMessage will decide if the message is intended for every window you target or only for a specific one (for example you could send messages that are only meant for your website, other embedding sites can then not receive the event. More infos on restricting the target here.

Please ask if you have any questions :)