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.
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):
And you send these messages from the embedded iframe website with the
postMessage
function like this for posting to the parent window (embedding window)For the other way around, you embed the page like this, the name has to be unique
And then you can send a post with this:
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 :)