Answer the question
In order to leave comments, you need to log in
How to pass data to dynamically created iFrame using postMessage?
I've already tried everything, I can't figure out what's wrong...
I'm making a widget that is installed on the site by connecting a JS script.
More or less like this:
<script src="//app.localhost/widget/v1" type="application/javascript"></script>
<script type="text/javascript">
var Widget116;
document.addEventListener("DOMContentLoaded", function() {
Widget116= new GoWidget({
id: 116,
openSelector: '.go-show-MnJa2hqMsFkRtBC',
autoOpen: false,
autoOpenDelay: 0,
openBeforeClose: false,
}).init()
});
</script>
// все что тут делается это в конец body вставляется frame
GoWidget.prototype.createWidget = function () {
var tt = this
var elWrapper, elModal, elWidget, elCurtain, elClose
elWrapper = document.createElement('div'),
elModal = document.createElement('div'),
elWidget = document.createElement('iframe')
elCurtain = document.createElement('div')
elClose = document.createElement('div')
elCurtain.className = 'b-start'
elClose.className = 'b-icon-close'
elWrapper.className = 'b-wrapper b-wrapper__' + tt.params.id
elModal.className = 'b-modal'
elWidget.setAttribute('id', 'iframe-widget-'+tt.params.id)
if (tt.params.noStatic){
elWidget.setAttribute('src', tt.assets.widgetUrl+'?noStatic=noStatic')
}else{
elWidget.setAttribute('src', tt.assets.widgetUrl)
}
elWrapper.appendChild(elModal)
elModal.appendChild(elClose)
elModal.appendChild(elCurtain)
elModal.appendChild(elWidget)
document.body.appendChild(elWrapper);
return this
}
GoWidget.prototype.setEvents = function () {
var this_ = this
setTimeout(function () {
var iframe = document.getElementById('iframe-widget-'+this_.params.id);
console.log('Call testMessage', iframe.contentWindow)
iframe.contentWindow.postMessage("onmessage", "http://app.localhost");
}, 3000)
return this
}
window.addEventListener('onmessage', function(event) {
console.log('onmessage get');
});
Answer the question
In order to leave comments, you need to log in
Are you sure the iframe has already loaded when the message is sent there? And that the right document was loaded there, and, for example, not ERROR 404?
The most reliable way to ensure that a frame is ready to receive messages is to send a message from the frame to the parent after it has registered onmessage with itself. And only after that send messages from the parent to the iframe. Up to this point, for example, they can be accumulated in a buffer.
maybe it will come in handy for someone, I found the answer here:
https://vexell.ru/%D0%BF%D0%B5%D1%80%D0%B5%D0%B4%D...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question