After reading multiple SO posts, I understand the best (or only) way to use javascript on an iFrame is by postMessage
and addEventListener
. All of the sample code I've found online show something like this:
<div id="magazine-container">
<iframe id="iFrame" height="500" width="700" src="https://issuu.com/lideres_mexicanos/docs/351grupoaries-issuu/76"></iframe>
</div>
<script>
$(document).ready(function () {
let testString = 'MESSAGE FROM LOCALHOST';
let frame = document.getElementById('iFrame');
frame.contentWindow.postMessage(testString, '*');
window.addEventListener('message', event => {
console.log(event.data);
});
});
</script>
Looking in the console, event.data
does not contain variable testString
.
Instead it contains this:
{"PrivacyManagerAPI":{"timestamp":1584457115641,"action":"getConsent","self":"quantserve.com","domain":"issuu.com","authority":"truste.com","type":"advertising"}}
I just can't figure out what's going on here.
Edit
I understand now that I wasn't attaching the addEventListener
to the iFrame, but to the parent. Is there a way to add the listener to the actual iFrame without having access to the source code to the page used in the iFrame?
When you're calling postMessage
on the frame's contentWindow you are sending a message to the iFrame, as I believe you intend.
However, you are adding an event listener to the parent window (aka window
), NOT the iframe's content window. The message that you are console.log
ing is not the one you sent, it is instead a different message that is being received by your page. This is likely either a response to the message you sent, or a message sent by a plugin you have installed on your browser.
To achieve the functionality of a parent communicating with a child iFrame, you must have access to the source code of the iframe so you can attach the event handler there, or be using a target with a defined API already set up.